Archived Forum Post

Index of archived forum posts

Question:

AES/CRT/NoPadding with 128bits key and a cipher salt

Sep 02 '15 at 14:39

I followed the example c# AES CTR Mode but unable to decrypt. I'm not sure about the PaddingScheme for "NoPadding"? Here is my code:

   crypt.CryptAlgorithm = "aes";
   crypt.CipherMode = "crt";
   crypt.KeyLength = 128;

   crypt.PaddingScheme = 0;
   crypt.EncodingMode = "base64";

   crypt.SetEncodedIV(CIPHER_SALT, "base64");
   crypt.SetEncodedKey(decryptedByteToString, "base64");

   string decBytes = crypt.DecryptString(Convert.FromBase64String(sPhoneAttributes));

Answer

See https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation for an explanation of block encryption cipher modes.

CTR mode is special in a few ways:

1) Padding doesn't apply. Normally, a block encryption algorithm (AES, Blowfish, DES, RC2, etc.) emit encrypted output that is a multiple of the block size (16 bytes for AES as an example). With CTR mode, the number of bytes output is exactly equal to the number of bytes input, so no padding/unpadding is required. The PaddingScheme property does not apply for counter mode.

2) CTR mode increments a counter for each subsequent block encrypted. For example, if an application encrypted the string "1234567890" twenty times in a row, using the same instance of the Chilkat Crypt2 object, then each iteration's result would be different. This is because the counter is being incremented. The decrypting application would need to decrypt in exactly the same manner. The 1st decrypt should begin with a new instance of a Crypt2 object so that it's counter is at the initial value of 0.

It would be a mistake to encrypt 20 strings using an instance of the Crypt2 object, and then attempt to decrypt with the same Crypt2 object. To decrypt successfully, the app would need to instantiate a new Crypt2 object and then decrypt, so that the counters match.