2

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.

Ryan B.
  • 1,270
  • 10
  • 24

1 Answers1

4

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.

Topaco
  • 40,594
  • 4
  • 35
  • 62
  • 1
    This random key is a good library design choice. If one sets a 128-bit key and then converts it to a 256-bit key the result is either unexpected or filled with 128-bit zeros. Instead, they made it random to mitigate possible security problems that is converted to the beginners coding problem. :) – kelalaka Aug 16 '22 at 19:17