我想在C# Windows Phone 8应用程序中使用AES/CBC/NoPadding解密加密的字符串。我的字符串在
从这篇文章中,我正在使用AesManaged类进行解密。 但如何将填充设置为
我认为问题出在IV[salt key]或将填充设置为AesManged上。 但我无法在Windows Phone中将填充属性更改为AesManaged。 默认情况下,AesManged的填充是
IsolatedStorage
文件中。我粘贴了这个链接,它是垃圾。从这篇文章中,我正在使用AesManaged类进行解密。 但如何将填充设置为
NoPadding
,因为默认情况下填充设置为PKCS7
,来自这里。 string fileName = "titlepage.xhtml";
if (fileStorage.FileExists(fileName))
{
IsolatedStorageFileStream someStream = fileStorage.OpenFile(fileName, System.IO.FileMode.Open, FileAccess.Read);
using (StreamReader reader = new StreamReader(someStream))
{
str1 = reader.ReadToEnd();
MessageBox.Show(str1);
try
{
string text = Decrypt(str1, "****************", "****************");
MessageBox.Show(text);
}
catch (CryptographicException cryptEx)
{
MessageBox.Show(cryptEx.Message, "Encryption Error", MessageBoxButton.OK);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "General Error", MessageBoxButton.OK);
}
}
}
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);
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();
}
}
编辑1:
当我在这行代码中解密加密字符串时
byte[] data = Convert.FromBase64String(dataToDecrypt);
移动到最终块
并获取异常:输入不是有效的Base-64字符串,因为它包含非Base-64字符、超过两个填充字符或填充字符中存在非法字符。
在Windows Phone中支持哪个类解密有点混淆。
如果我完全错误,请建议我有关Windows Phone算法的文章网址。
编辑2:
如下回答所建议的"我将cyperText作为字节获取,解密时没问题。但是它会抛出一个带有描述的异常。
[Cryptography_SSD_InvalidDataSize]
Arguments:
Debugging resource strings are unavailable. Often the key and arguments provide
sufficient information to diagnose the problem
我认为问题出在IV[salt key]或将填充设置为AesManged上。 但我无法在Windows Phone中将填充属性更改为AesManaged。 默认情况下,AesManged的填充是
PKCS7
。我想要更改为NoPadding
。因为我的cyperText是使用AES/CBC/NoPadding算法加密的。