我有一个使用system.security.cryptography加密和解密消息的程序。在加密消息时,它可以正常工作,但是在解密消息时,它却无法做到这一点,因此,解码后的消息只是怪异的符号和乱码。它在任何地方都没有给出任何例外,因此我无法弄清楚问题是什么。
public static byte[] EncryptStringToBytes_Aes(string plainText)
{
try
{
byte[] encrypted;
using (AesManaged aesAlg = new AesManaged())
{
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
using (var msEncrypt = new MemoryStream())
using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
using (var swEncrypt = new StreamWriter(csEncrypt))
{
swEncrypt.Write(plainText);
csEncrypt.FlushFinalBlock();
encrypted = msEncrypt.ToArray();
}
}
// Return the encrypted bytes from the memory stream.
return encrypted;
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
return null;
}
public static string DecryptStringFromBytes_Aes(byte[] cipherText)
{
try
{
// Declare the string used to hold
// the decrypted text.
string plaintext = null;
// Create an AesManaged object
// with the specified key and IV.
using (AesManaged aesAlg = new AesManaged())
{
//aesAlg.Key = Key;
//aesAlg.IV = IV;
aesAlg.Padding = PaddingMode.None;
// Create a decryptor to perform the stream transform.
ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
// Create the streams used for decryption.
using (var msDecrypt = new MemoryStream(cipherText))
using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
using (var srDecrypt = new StreamReader(csDecrypt))
{
plaintext = srDecrypt.ReadToEnd();
}
}
return plaintext;
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
return null;
}
任何想法可能是什么问题?谢谢