Encryption operation mode and the padding scheme should be chosen appropriately to guarantee data confidentiality, integrity and authenticity:
- For block cipher encryption algorithms (like AES):
- The GCM (Galois Counter Mode) mode which works
internally with zero/no padding scheme, is recommended, as it is designed to provide both data authenticity (integrity) and confidentiality.
Other similar modes are CCM, CWC, EAX, IAPM and OCB.
- The CBC (Cipher Block Chaining) mode by itself provides only data confidentiality, it’s recommended to use it along with Message
Authentication Code or similar to achieve data authenticity (integrity) too and thus to prevent padding oracle attacks.
- The ECB (Electronic Codebook) mode doesn’t provide serious message confidentiality: under a given key any given plaintext block always gets
encrypted to the same ciphertext block. This mode should not be used.
- For RSA encryption algorithm, the recommended padding scheme is OAEP.
Noncompliant Code Example
AesManaged object with
AesManaged aes4 = new AesManaged
KeySize = 128,
BlockSize = 128,
Mode = CipherMode.ECB, // Noncompliant
Padding = PaddingMode.PKCS7
object without OAEP padding:
RSACryptoServiceProvider RSA1 = new RSACryptoServiceProvider();
encryptedData = RSA1.Encrypt(dataToEncrypt, false); // Noncompliant: OAEP Padding is not used (second parameter set to false)
AES with GCM mode with bouncycastle library:
GcmBlockCipher blockCipher = new GcmBlockCipher(new AesEngine()); // Compliant
blockCipher.Init(true, new AeadParameters(new KeyParameter(secretKey), 128, iv, null));
AES with GCM mode with AesGcm
var aesGcm = new AesGcm(key); // Compliant
RSA with OAEP padding with RSACryptoServiceProvider
RSACryptoServiceProvider RSA2 = new RSACryptoServiceProvider();
encryptedData = RSA2.Encrypt(dataToEncrypt, true); // Compliant: OAEP Padding is used (second parameter set to true)