I am using symmetric TripleDES encryption from the class TripleDESCryptoServiceProvider (.Net 2.0) to encrypt the contents of a file. The data gets encrypted perfectly but during decryption it throws the CryptographyException: Bad data
I am using key from current date time and IV from the randomly generated value by .Net class. Then I pass the same key and IV to the decryption method but it fails for some reason.
Here is my code :
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;
}
UPDATE:
1. I have checked the value of IV being passed is valid and same as used in encryption.
2. Changing the padding to zero or none doesn't raise the exception but then the data isn't decrypted correctly. It comes out to be different than original.
tdes
. – initramfs