다음 코드를 가지고 있으며 거의 2 년간 작동했습니다. 그러나 이제 우리는 Padding에 대한 임의의 문제를보기 시작했습니다. 내가 무작위로 말할 때, 나는 같은 일이 어느 날 일하지만 다른 날에는 일하지 않는다는 것을 의미합니다. 그리고 언젠가는 무작위로 일하기로 결정합니다.기존 암호화/암호 해독 코드에서 패딩 옵션을 변경하는 방법은 무엇입니까?
위의 답변에서 언급 한 것처럼 패딩을 추가하지 않으면 이전에 암호화 된 파일을 모두 망칠 수 있습니다. 나는 다른 방법을 GOTO 문을 사용하여 catch 블록에서이 방법으로 만들 때와 같은 방법으로 암호화 키를 변경했을 때 생각했다. 또는 은 패딩을 None으로 변경하는 더 좋은 방법이 있습니까?
/// <summary>
///
/// </summary>
[Serializable]
public static class EncryptDecrypt
{
private static string EncryptionKey_old = "MAKV2SPBNI99212";
private static string EncryptionKey = "Yi9BpGG1cXR01gBwGPZRTOznoJHpkGBOzisBg5jl3iRu48yhcFGdZu76fDpa5FUu";
/// <summary>
///
/// </summary>
/// <param name="clearText"></param>
/// <returns></returns>
public static string Encrypt(string clearText)
{
byte[] whitebs = Encoding.Unicode.GetBytes(clearText);
using (Aes encryptor = Aes.Create())
{
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
encryptor.Key = pdb.GetBytes(32);
encryptor.IV = pdb.GetBytes(16);
encryptor.Mode = CipherMode.ECB;
encryptor.Padding = PaddingMode.PKCS7;
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(whitebs, 0, whitebs.Length);
cs.FlushFinalBlock();
cs.Close();
}
clearText = Convert.ToBase64String(ms.ToArray());
}
}
return clearText.EndsWith("==") ? clearText.Remove(clearText.Length - 2) : clearText;
}
/// <summary>
///
/// </summary>
/// <param name="cipherText"></param>
/// <returns></returns>
public static string Decrypt(string cipherText)
{
int attempts = 0;
string exception = string.Empty;
StartHere:
cipherText = cipherText.Replace(" ", "+");
byte[] cipherBytes;
try { cipherBytes = Convert.FromBase64String(cipherText); }
catch { cipherBytes = Convert.FromBase64String(cipherText + "=="); }
using (Aes encryptor = Aes.Create())
{
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
encryptor.Key = pdb.GetBytes(32);
encryptor.IV = pdb.GetBytes(16);
encryptor.Mode = CipherMode.ECB;
encryptor.Padding = PaddingMode.PKCS7;
try
{
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
{
cs.Write(cipherBytes, 0, cipherBytes.Length);
cs.FlushFinalBlock();
cs.Close();
}
cipherText = Encoding.Unicode.GetString(ms.ToArray());
}
}
catch
{
if (attempts == 2) throw;
EncryptionKey = EncryptionKey_old;
attempts++;
goto StartHere;
}
}
return cipherText;
}
'
또한 우리가이 코드를 사용하여 암호화 된 파일의 수천이 있기 때문에 내가 그 일에 대해 갈 것입니다 방법을 모르는 좋은 생각이 아니다 지금 변경.
이인가요 올바른 패딩입니다 방금 공개 인터넷에 올린 하드 코드 된 암호화 키가 있습니까? – Blorgbeard
아니, 이전 하나는 진짜지만 더 이상 사용되지 않았습니다. –
대신 왜 이러한 패딩 문제가 발생하는지 파악하려고합니다. 그 사실을 알면 다른 것을 바꾸는 것에 대해 걱정할 필요가 없습니다. 당신은 잘못된 방식으로 문제에 접근하고 있습니다. –