【发布时间】:2016-08-28 05:38:24
【问题描述】:
我已经实现了代码加密和解密方法。输入字符串值传递给 encrypt 方法并获取存储在 xml 文件中的加密值。在我获得加密值以使用解密方法读取 xml 文件来读取值之后。在极少数情况下我收到错误(加密的输入值不正确且解密的输出值)。我该如何解决这个问题。请分享给我。 这里是示例代码
public static string Decrypt(string cipherText)
{
try
{
string incoming = cipherText.Replace('_', '/').Replace('-', '+');
switch (cipherText.Length % 4)
{
case 2: incoming += "=="; break;
case 3: incoming += "="; break;
}
byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector);
byte[] cipherTextBytes = Convert.FromBase64String(incoming);
PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, null);
byte[] keyBytes = password.GetBytes(keysize / 8);
RijndaelManaged symmetricKey = new RijndaelManaged();
symmetricKey.Mode = CipherMode.CBC;
ICryptoTransform decryptor = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes);
MemoryStream memoryStream = new MemoryStream(cipherTextBytes);
CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);
byte[] plainTextBytes = new byte[cipherTextBytes.Length];
int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
memoryStream.Close();
cryptoStream.Close();
return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
}
catch (Exception ex)
{
return "Exception";
}
}
【问题讨论】:
-
将 Ascii 编码更改为 UTF8 编码。带有删除不可打印字符的 Ascii 编码。我怀疑加密有时会生成 Ascii 编码正在删除的字符。
标签: c#