我已經實現了代碼加密和解密方法。輸入字符串值傳遞給加密方法並獲取存儲在xml文件中的加密值。在獲得加密值後,使用Decrypt Method讀取xml文件來讀取值。在罕見的情況下,我收到錯誤(加密的輸入值不正確並且解密輸出值)。我該如何解決這個問題。請分享給我。 下面的示例代碼使用c#中的rijindeal algorthm加密解密時丟失的字符
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編碼消除的字符。 – jdweng