我已经使用这个网站实现了 AES 算法。https://msdn.microsoft.com/en-us/library/system.security.cryptography.aesmanaged(v=vs.110).aspx
加密后将值转换为字符串并发送到数据库。这是成功的。当我检索值 Encrypted 值时,这是成功的。但是当我开始解密时,没有发现错误,也没有显示输出(使用消息框获取输出)。我应该怎么办?
byte[] cipherbytes = System.Text.ASCIIEncoding.Default.GetBytes(encypted);
//AES Decryption start
try
{
using (AesManaged myAes = new AesManaged())
{
// Decrypt the bytes to a string.
string roundtrip = DecryptStringFromBytes_Aes(cipherbytes, myAes.Key, myAes.IV);
//Console.WriteLine("Round Trip: {0}", roundtrip);
MessageBox.Show(roundtrip, "Decrypted text"); //this meessage box is not showing
}
}
catch (Exception e)
{
Console.WriteLine("Error: {0}", e.Message);
//MessageBox.Show("Inside is working");
}
//这里也是解密算法
static string DecryptStringFromBytes_Aes(byte[] cipherText, byte[] Key, byte[] IV)
{
// Check arguments.
if (cipherText == null || cipherText.Length <= 0)
throw new ArgumentNullException("cipherText");
if (Key == null || Key.Length <= 0)
throw new ArgumentNullException("Key");
if (IV == null || IV.Length <= 0)
throw new ArgumentNullException("IV");
// 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;
// Create a decrytor to perform the stream transform.
ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
// Create the streams used for decryption.
using (MemoryStream msDecrypt = new MemoryStream(cipherText))
{
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
{
// Read the decrypted bytes from the decrypting stream
// and place them in a string.
plaintext = srDecrypt.ReadToEnd();
}
}
}
}