Playing around with 3DES encryptions and decryptions, I use this fairly simple and standard code. However, I get different decryptionData
value as output everytime I run this function.
Can someone point me what's wrong?
private void TripleDESDecryption()
{
TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider();
des.Key = new byte[] { 0x26, 0x01, 0x54, 0xd0, 0xdc, 0x92, 0xf3, 0x4b, 0xbf, 0x9b, 0xfa, 0x9d, 0x43, 0x24, 0x4b, 0xa4, 0x35, 0x50, 0xde, 0x00, 0x5e, 0x75, 0xc7, 0xed };
des.KeySize = 192;
des.Mode = CipherMode.ECB;
des.Padding = PaddingMode.None;
ICryptoTransform ic = des.CreateDecryptor();
var encryptedData = new byte[] { 0x35, 0x66, 0x45, 0xC4, 0xBD, 0xE9, 0x5F, 0x30 };
byte[] decryptedData = ic.TransformFinalBlock(encryptedData, 0, 8);
Console.WriteLine(BitConverter.ToString(decryptedData));
}
PS: These are just random keys and data, no sensitive stuff.
CodePudding user response:
For the TripleDESCryptoServiceProvider.KeySize
property applies:
Changing the KeySize value resets the key and generates a new random key. This happens whenever the KeySize property setter is invoked (including when it's assigned the same value).
Therefore, in the posted code, the originally set key is overwritten by a randomly generated key, which is why a different result is generated each time. Fix: Remove the explicit KeySize
call. This is not necessary, because the key size is implicitly set with the key.
Note that Triple DES is outdated and ECB is insecure.