I have a problem with decryption of data previously encrypted. I am using the sequential encrypt-decrypt-encrypt with three different keys to get triple des effect. The encryption function works correctly (returns 8-byte array), but the decryption function returns empty array.
public static byte[] EncryptDES(byte[] clearData, byte[] key)
{
DES desEncrypt = new DESCryptoServiceProvider();
desEncrypt.Mode = CipherMode.ECB;
desEncrypt.Key = key;
ICryptoTransform transForm = desEncrypt.CreateEncryptor();
MemoryStream encryptedStream = new MemoryStream();
CryptoStream cryptoStream = new CryptoStream(encryptedStream, transForm, CryptoStreamMode.Write);
cryptoStream.Write(clearData, 0, clearData.Length);
byte [] encryptedData = encryptedStream.ToArray();
return encryptedData;
}
public static byte[] DecryptDES(byte[] clearData, byte[] key)
{
DES desDecrypt = new DESCryptoServiceProvider();
desDecrypt.Mode = CipherMode.ECB;
desDecrypt.Key = key;
ICryptoTransform transForm = desDecrypt.CreateDecryptor();
MemoryStream decryptedStream = new MemoryStream();
CryptoStream cryptoStream = new CryptoStream(decryptedStream, transForm, CryptoStreamMode.Write);
cryptoStream.Write(clearData, 0, clearData.Length);
byte[] encryptedData = decryptedStream.ToArray();
return encryptedData;
}
public static byte[] Encrypt3DES(byte[] clearData, byte[] key0, byte[] key1, byte[] key2)
{
byte[] encryptedData1 = new byte[clearData.Length];
byte[] encryptedData2 = new byte[clearData.Length];
byte[] encryptedData3 = new byte[clearData.Length];
encryptedData1 = DESCrypto.EncryptDES(clearData , key0);
encryptedData2 = DESCrypto.DecryptDES(encryptedData1, key1);
encryptedData3 = DESCrypto.EncryptDES(encryptedData2, key2);
return encryptedData3;
}
What am I doing wrong?
TripleDES already exist in the Framework but I guess you want to roll your own implementation for educational purposes.
You're making things more complicated than necessary. Since you are using streams why don't you chain them all instead:
Make note of the usage of
using
blocks and also how the padding is applied to the different streams.The framework TripleDES is about 2.5 times faster than the above code.
If you want to compare the results of the two different encryption methods then you need to remember that the 24-bit key for TripleDES is actually the 3 keys put in one array: