간단한 문자열 암호화가 필요해서 다음 코드를 작성했습니다(여기에서 많은 '영감'을 얻었습니다):
// create and initialize a crypto algorithm
private static SymmetricAlgorithm getAlgorithm(string password) {
SymmetricAlgorithm algorithm = Rijndael.Create();
Rfc2898DeriveBytes rdb = new Rfc2898DeriveBytes(
password, new byte[] {
0x53,0x6f,0x64,0x69,0x75,0x6d,0x20, // salty goodness
0x43,0x68,0x6c,0x6f,0x72,0x69,0x64,0x65
}
);
algorithm.Padding = PaddingMode.ISO10126;
algorithm.Key = rdb.GetBytes(32);
algorithm.IV = rdb.GetBytes(16);
return algorithm;
}
/*
* encryptString
* provides simple encryption of a string, with a given password
*/
public static string encryptString(string clearText, string password) {
SymmetricAlgorithm algorithm = getAlgorithm(password);
byte[] clearBytes = System.Text.Encoding.Unicode.GetBytes(clearText);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, algorithm.CreateEncryptor(), CryptoStreamMode.Write);
cs.Write(clearBytes, 0, clearBytes.Length);
cs.Close();
return Convert.ToBase64String(ms.ToArray());
}
/*
* decryptString
* provides simple decryption of a string, with a given password
*/
public static string decryptString(string cipherText, string password) {
SymmetricAlgorithm algorithm = getAlgorithm(password);
byte[] cipherBytes = Convert.FromBase64String(cipherText);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, algorithm.CreateDecryptor(), CryptoStreamMode.Write);
cs.Write(cipherBytes, 0, cipherBytes.Length);
cs.Close();
return System.Text.Encoding.Unicode.GetString(ms.ToArray());
}
코드가 정상적으로 작동하는 것처럼 보이지만, 잘못된 키가 포함된 데이터를 해독할 때 decryptString의 cs.Close() 줄에서 CryptographicException - "패딩이 유효하지 않으며 제거할 수 없습니다"-이 발생합니다.
예제 코드:
string password1 = "password";
string password2 = "letmein";
string startClearText = "The quick brown fox jumps over the lazy dog";
string cipherText = encryptString(startClearText, password1);
string endClearText = decryptString(cipherText, password2); // exception thrown
제 질문은 이것이 예상되는 일인가요? 잘못된 비밀번호로 암호를 해독하면 예외가 아니라 그냥 말도 안 되는 출력이 나올 것이라고 생각했을 것입니다.
이미 답변한 내용이지만 왜 그렇게 예상되는지 설명하는 것이 좋을 것 같습니다.
패딩 체계는 일반적으로 대부분의 암호화 필터가 의미론적으로 안전하지 않기 때문에 일부 형태의 크립토어택을 방지하기 위해 적용됩니다. 예를 들어, 일반적으로 RSA에서는 선택된 평문 공격 또는 블라인드 공격과 같은 일부 종류의 공격을 방지하는 OAEP 패딩 체계가 사용됩니다.
패딩 방식은 메시지가 전송되기 전에 메시지 m에 (보통) 임의의 가비지를 추가합니다. 예를 들어 OAEP 방식에서는 두 개의 오라클이 사용됩니다(이것은 간단한 설명입니다):
이렇게 하면 메시지에 대한 무작위화와 메시지가 가비지인지 아닌지 테스트할 수 있는 방법이 제공됩니다. 패딩 방식은 가역적이기 때문에 메시지 자체의 무결성에 대해서는 아무 말도 할 수 없지만 메시지를 해독할 때 패딩에 대해 어떤 주장을 할 수 있으므로 메시지가 올바르게 해독되었는지 또는 잘못된 작업(즉, 누군가 메시지를 변조했거나 잘못된 키를 사용 중인지)을 하고 있는지 알 수 있습니다.
저도 비슷한 경험이 " 올바르지 않으며, 패딩 removed." 수 없습니다. 내 경우에는 예외가 있지만 정확한 키를 IV) 와 패딩 있었다.
Ts 는 암호화 플러시하는 것으로 드러나 이 모든 것이 없습니다.
다음과 같습니다.
MemoryStream msr3 = new MemoryStream();
CryptoStream encStream = new CryptoStream(msr3, RijndaelAlg.CreateEncryptor(), CryptoStreamMode.Write);
encStream.Write(bar2, 0, bar2.Length);
// unless we flush the stream we would get "Padding is invalid and cannot be removed." exception when decoding
encStream.FlushFinalBlock();
byte[] bar3 = msr3.ToArray();
올바른 것으로 사용 스케쳐내 추가해야 합니다 인증 데이터베이스에구성원을 수 있도록 하는 것이 올바른 암호 enable-volume-set 암호화 텍스트 또는 암호화 텍스트 hasn& # 39, t 수정되었습니다. 패딩 [ISO10126] [2] 에서는 사용 중인 경우 예외가 doesn& 중 하나로, t # 39 마지막 바이트입니다 해독할 16 유효값 패딩에 (0x01 0x10). 그래서 니말은 1/16 투명지에 가능성이 있는 것은 잘못된 암호를 사용하여 공을 idfsysobject. 인증하려고 경우 이를 확인할 수 있는 경우 경우 강력한 암호 해독 유효합니다.
이러한 이유로 쉽게 만들 수 있는 실수, I have a 코드를 시도하시겠습니까 스니핏, 내가 계속 검토됨 및 최신임 (주석, 문제 itopia):
[2]: # iso10126 http://en.wikipedia.org/wiki/padding% 28cryptography% 29
'반드시 함께 사용하는 경우 엄격히 지우는중 리소스에는' 블록 '블록' 자체에 대한 중첩할 크라이프트로스트림.
using (MemoryStream ms = new MemoryStream())
using (var enc = RijndaelAlg.CreateEncryptor())
{
using (CryptoStream encStream = new CryptoStream(ms, enc, CryptoStreamMode.Write))
{
encStream.Write(bar2, 0, bar2.Length);
} // implicit close
byte[] encArray = ms.ToArray();
}
using (MemoryStream ms = new MemoryStream())
using (var enc = RijndaelAlg.CreateEncryptor())
using (CryptoStream encStream = new CryptoStream(ms, enc, CryptoStreamMode.Write))
{
encStream.Write(bar2, 0, bar2.Length);
byte[] encArray = ms.ToArray();
} // implicit close -- too late!
또 다른 이유도 간 해독 논리를 사용하여 여러 스래드입니다 idfsysobject. 경합이 될 수 없습니다 - 기본 구현을 이스라이프트로트란스포르마 스레드 있다 (예를 들면 시메트리칼고리스만) 사용할 수 있는 전용 섹션을 둘 것인지, 그렇게 잠급니다. (예: 자세한 내용은 여기 참조하십시오. http://www.make-awesome.com/2011/07/system-security-cryptography-and-thread-safety/