Triple DES encryption

user725913 picture user725913 · Aug 9, 2011 · Viewed 6.9k times · Source

Please note that the issue I am having here is with the key size. At first, based on the comments included in the below code, I figured that my key needed to be 24 bytes (192 bits). This didn't work so I gave 16, 32, and 8 byte keys a shot - nothing seems to be working. By "not working" I mean that after my text has been encrypted and decrypted it does not hold the same value as my original text.

Example:

Original Text: 'Example test this should work '

Encrypted Text: ¸¹pÕô6

Decrypted Text: 'Example '

Here are the two functions I am using (Encrypt / Decrypt functions). Also I will include how I am calling each function.

        // 168-bit (three-key) 3DES (Triple-DES) encrypt a single 8-byte block (ECB mode)
        // plain-text should be 8-bytes, key should be 24 bytes.
        public byte[] TripleDesEncryptOneBlock(byte[] plainText, byte[] key)
        {
            // Create a new 3DES key.
            TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider();

            // Set the KeySize = 192 for 168-bit DES encryption.
            // The msb of each byte is a parity bit, so the key length is actually 168 bits.

            des.KeySize = 192;
            des.Key = key;
            des.Mode = CipherMode.ECB;
            des.Padding = PaddingMode.None;

            ICryptoTransform ic = des.CreateEncryptor();

            byte[] enc = ic.TransformFinalBlock(plainText, 0, 8);

            return enc;
        }

        public byte[] TripleDesDecryptBlock(byte[] plainText, byte[] key)
        {
            // Create a new 3DES key.
            TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider();

            // Set the KeySize = 192 for 168-bit DES encryption.
            // The msb of each byte is a parity bit, so the key length is actually 168 bits.
            des.KeySize = 192;
            des.Key = key;
            des.Mode = CipherMode.ECB;
            des.Padding = PaddingMode.None;

            ICryptoTransform ic = des.CreateDecryptor();

            byte[] dec = ic.TransformFinalBlock(plainText, 0, 8);

            return dec;
        }

// Encrypt Text
textBox5.Text = ByteToString(TripleDesEncryptOneBlock(StringToByte(textBox5.Text), StringToByte("1 2 3 4 5 6 7 8 9 1 1 2 ")));

// Decrypt Text
textBox5.Text = ByteToString(TripleDesDecryptBlock(StringToByte(textBox5.Text), StringToByte("1 2 3 4 5 6 7 8 9 1 1 2 ")));

Thank you for any help,

Evan

Answer

Andrew Cooper picture Andrew Cooper · Aug 9, 2011

The clue is in the name of the function you're using: TripleDesEncryptOneBlock

This method only encrypts one block of the input string (8 bytes or 64 bits). To encrypt the entire string you need to chain multiple calls to this method.