我使用TripleDESCryptoServiceProvider(.Net 2.0)类中的对称TripleDES加密来加密文件的内容。 数据被完美加密,但在解密过程中会抛出 CryptographyException:Bad data
我使用当前日期时间的密钥和来自.Net类随机生成的值的IV。然后我将相同的密钥和IV传递给解密方法,但由于某种原因它失败了。
这是我的代码:
static void Main(string[] args){
string fileName = "input.exe";
string newFileName = fileName + "crypted.exe";
byte[] iv;
var fileToEncrypt = File.ReadAllBytes(fileName);
var encryptionKey = MD5.Create().ComputeHash(Encoding.UTF8.GetBytes(DateTime.Now.ToString("ddMMyyHmmss")));
File.WriteAllBytes(newFileName, EncryptTripleDES(fileToEncrypt, encryptionKey, out iv));
File.WriteAllBytes(fileName + "decrypted.exe", DecryptTripleDES(File.ReadAllBytes(newFileName), encryptionKey,iv));
}
public static byte[] EncryptTripleDES(byte[] dataToEncrypt, byte[] key, out byte[] iv){
byte[] result;
var tdes = new TripleDESCryptoServiceProvider { Key = key, KeySize = 128, Mode = CipherMode.CBC, Padding = PaddingMode.PKCS7 };
iv = tdes.IV;
using(ICryptoTransform cTransform = tdes.CreateEncryptor()){
result = cTransform.TransformFinalBlock(dataToEncrypt, 0, dataToEncrypt.Length);
tdes.Clear();
}
return result;
}
public static byte[] DecryptTripleDES(byte[] dataToDecrypt, byte[] key, byte[] iv){
byte[] result;
var tdes = new TripleDESCryptoServiceProvider { Key = key, KeySize = 128, Mode = CipherMode.CBC,IV = iv,Padding = PaddingMode.PKCS7 };
using (ICryptoTransform cTransform = tdes.CreateDecryptor()){
result = cTransform.TransformFinalBlock(dataToDecrypt, 0, dataToDecrypt.Length);
tdes.Clear();
}
return result;
}
的更新:
1.我已检查传递的IV值是否有效且与加密时使用的值相同。
2.将填充更改为零或无,不会引发异常,但数据未正确解密。它与原来不同。
答案 0 :(得分:1)
问题在于您使用初始化程序构建TripleDESCryptoServiceProvider
的方式。首先在初始值设定项中设置Key
,然后设置KeySize
,这会导致Key
重置为新的(随机生成的)密钥,因此,您&# 39;用不同的密钥重新加密和解密(两者都不是你生成的key
。
您可以通过重新排序初始化程序来解决此问题,以便首先设置KeySize
,或者可以将Key
的设置完全移出初始化程序以避免任何歧义:
public static byte[] EncryptTripleDES(byte[] dataToEncrypt, byte[] key, out byte[] iv){
byte[] result;
var tdes = new TripleDESCryptoServiceProvider { KeySize = 128, Mode = CipherMode.CBC, Padding = PaddingMode.PKCS7 };
// Key explicitly set here, not in the initializer:
tdes.Key = key;
iv = tdes.IV;
using(ICryptoTransform cTransform = tdes.CreateEncryptor()){
result = cTransform.TransformFinalBlock(dataToEncrypt, 0, dataToEncrypt.Length);
tdes.Clear();
}
return result;
}
public static byte[] DecryptTripleDES(byte[] dataToDecrypt, byte[] key, byte[] iv){
byte[] result;
var tdes = new TripleDESCryptoServiceProvider { KeySize = 128, Mode = CipherMode.CBC,IV = iv,Padding = PaddingMode.PKCS7 };
// Key explicitly set here, not in the initializer:
tdes.Key = key;
using (ICryptoTransform cTransform = tdes.CreateDecryptor()){
result = cTransform.TransformFinalBlock(dataToDecrypt, 0, dataToDecrypt.Length);
tdes.Clear();
}
return result;
}