我正在尝试解密windows 8中的字符串。但是,它不可避免地给了我以下错误
System.Security.Cryptography.CryptographicException:填充无效,无法删除。在System.Security.Cryptography.RijndaelManagedTransform.DecryptData(Byte[] inputBuffer,Int32 inputOffset,Int32 inputCount,Byte[]& outputBuffer,Int32 outputOffset,PaddingMode paddingMode,Boolean )在System.Security.Cryptography.RijndaelManagedTransform.TransformFinalBlock(Byte[] inputBuffer,paddingMode paddingMode,paddingMode,inputBuffer)(在SampleAESEncryption.AES256.Decrypt)。( System.Windows.Controls.Primitives.ButtonBase.OnClick() at System.Windows.Controls.Button.OnClick() at System.Windows.Controls.Primitives.ButtonBase.OnMouseLeftButtonUp(MouseButtonEventArgs e) at System.Windows.Controls.Control.OnMouseLeftButtonUp(Control ctrl,EventArgs e) at 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();
}
}我试了很多次,但没能解决这个问题。我怎么才能解决这个问题?我的解密方法有什么问题吗?
发布于 2014-03-24 07:03:19
Convert.ToBase64String(Encoding.UTF8.GetBytes(txtText.Text.Trim()));这几乎肯定是个错误。您应该使用Convert.FromBase64从数据中获取一个字节数组,对其进行解密,然后使用Encoding.UTF8.GetString将结果转换为字符串。加密时,另一种方法是:用Encoding.UTF8.GetBytes获取字节,对它们进行加密,然后将结果转换为Convert.ToBase64String字符串。
https://stackoverflow.com/questions/22602238
复制相似问题