【发布时间】:2014-03-24 06:13:56
【问题描述】:
我正在尝试在 windows phone 8 中解密字符串。但不幸的是它给了我以下错误
System.Security.Cryptography.CryptographicException:填充无效且无法删除。 在 System.Security.Cryptography.RijndaelManagedTransform.DecryptData(Byte[] inputBuffer, Int32 inputOffset, Int32 inputCount, Byte[]& outputBuffer, Int32 outputOffset, PaddingMode paddingMode, Boolean fLast) 在 System.Security.Cryptography.RijndaelManagedTransform.TransformFinalBlock(字节 [] inputBuffer,Int32 inputOffset,Int32 inputCount) 在 System.Security.Cryptography.CryptoStream.FlushFinalBlock() 在 SampleAESEncryption.AES256.Decrypt(字符串 dataToDecrypt,字符串密码,字符串盐) 在 SampleAESEncryption.MainPage.btnDecrypt_Click(对象发送者,RoutedEventArgs e) 在 System.Windows.Controls.Primitives.ButtonBase.OnClick() 在 System.Windows.Controls.Button.OnClick() 在 System.Windows.Controls.Primitives.ButtonBase.OnMouseLeftButtonUp(MouseButtonEventArgs e) 在 System.Windows.Controls.Control.OnMouseLeftButtonUp(控制 ctrl,EventArgs e) 在 MS.Internal.JoltHelper.FireEvent(IntPtr unmanagedObj, IntPtr unmanagedObjArgs, Int32 argsTypeIndex, Int32 actualArgsTypeIndex, String eventName)
这是我的代码。 txtText.Text 是 256 位加密的。
txtText.Text = "Y5tq+5Smr13ChO2KYTOxvbCBlRTIDFXf+Ott2Euq+HiXTHDtUXn2+E46CYCGSC7P";
private void btnDecrypt_Click(object sender, RoutedEventArgs e)
{
AES256 encryptor = new AES256();
string strBase64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(txtText.Text.Trim()));
string decryptedString = encryptor.Decrypt(strBase64, "12345678", "12345678");
txtText.Text = decryptedString;
}
解密方法
public string Decrypt(string dataToDecrypt, string password, string salt)
{
AesManaged aes = null;
MemoryStream memoryStream = null;
try
{
//Generate a Key based on a Password and HMACSHA1 pseudo-random number generator
//Salt must be at least 8 bytes long
//Use an iteration count of at least 1000
Rfc2898DeriveBytes rfc2898 = new Rfc2898DeriveBytes(password, Encoding.UTF8.GetBytes(salt), 10000);
//Create AES algorithm
aes = new AesManaged();
//Key derived from byte array with 32 pseudo-random key bytes
aes.Key = rfc2898.GetBytes(32);
//IV derived from byte array with 16 pseudo-random key bytes
aes.IV = rfc2898.GetBytes(16);
//Create Memory and Crypto Streams
memoryStream = new MemoryStream();
CryptoStream cryptoStream = new CryptoStream(memoryStream, aes.CreateDecryptor(), CryptoStreamMode.Write);
//Decrypt Data
byte[] data = Convert.FromBase64String(dataToDecrypt);
cryptoStream.Write(data, 0, data.Length);
cryptoStream.FlushFinalBlock();
//Return Decrypted String
byte[] decryptBytes = memoryStream.ToArray();
//Dispose
if (cryptoStream != null)
cryptoStream.Dispose();
//Retval
return Encoding.UTF8.GetString(decryptBytes, 0, decryptBytes.Length);
}
finally
{
if (memoryStream != null)
memoryStream.Dispose();
if (aes != null)
aes.Clear();
}
}
我尝试了很多但无法解决这个问题。我该如何解决这个问题?我的 decrypt 方法有什么问题吗?
【问题讨论】:
标签: c# encryption windows-phone-8 aes