我是加密概念的新手。我试图使用AES加密来加密似乎工作正常的文件。但是当我使用解密时,我没有错误,但数据没有被解密。解密代码在
之下public static string DecryptData(string sFileInPath, byte[] Key, byte[] IV)
{
String data = null;
byte[] file = File.ReadAllBytes(sFileInPath);
if (!File.Exists(sFileInPath))
throw new ArgumentNullException("FilenotExists");
if (Key == null || Key.Length <= 0)
throw new ArgumentNullException("Key");
if (IV == null || IV.Length <= 0)
throw new ArgumentNullException("Key");
try
{
using (AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider())
{
aesAlg.Padding = PaddingMode.None;
aesAlg.Key = Key;
aesAlg.IV = IV;
aesAlg.Mode = CipherMode.CBC;
ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
MemoryStream ms = new MemoryStream();
using (var cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Write))
{
cs.Write(file, 0, file.Length);
cs.Close();
}
data = Encoding.Unicode.GetString(ms.ToArray());
msDecrypt.Close();
}
return data;
}
catch (Exception ex)
{
string status = string.Format("{0}: {1}", statustype.Failed.ToString(), ex.ToString());
return status;
}
}
调用解密方法
AesCryptoServiceProvider oAes = new AesCryptoServiceProvider();
string xml = Utility.DecryptData_AES(sfile,oAes.Key,oAes.IV);
加密方法:
public static byte[] EncryptData(AlertEnvelope alertenvelope, byte[] Key, byte[] IV)
{
if (alertenvelope == null)
throw new ArgumentNullException("alertenvelope");
if (Key == null || Key.Length <= 0)
throw new ArgumentNullException("Key");
if (IV == null || IV.Length <= 0)
throw new ArgumentNullException("Key");
byte[] encrypted;
using (AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider())
{
aesAlg.Padding = PaddingMode.PKCS7;
aesAlg.Key = Key;
aesAlg.IV = IV;
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
//Write all data to the stream.
swEncrypt.Write(alertenvelope);
}
encrypted = msEncrypt.ToArray();
}
}
}
return encrypted;
}
如果有人能帮助我理解数据未被解密的原因,我将不胜感激