Recipe Name:
Data Protection - Secure Data Storage: Avoid data exposure: Use Cipher instead of NullCipher
Description:
Could lead to data exposure
Level:
error
Language:
  • java
Tags:
  • security
  • basic protection set
Documentation

Out of best practices and android coding guidelines, recommendations were abstracted which state that NullCipher should never be used.

The NullCipher class is a class that provides an "identity cipher" — one that does not tranform the plaintext. As a consequence, the ciphertext is identical to the plaintext. This is highly insecure and should never be used. Use Cipher with recommended algorithm, mode and padding instead. Symmetric encryption should be used for bulk encryption, i.e. to store sensitive data securely or to encrypt communication after a secure channel has been established. The recommended algorithm for local storage is AES, used in GCM mode with no padding.

Correct code example
public static byte[] encryptForLocalStorage(byte[] plainText, byte[] IV, Key key) throws Exception {
    Cipher c = Cipher.getInstance("AES/GCM/NoPadding");
    GCMParameterSpec gcmSpec = new GCMParameterSpec(GCM_TAG_LENGTH * 8, IV);
    c.init(Cipher.ENCRYPT_MODE, key, gcmSpec);
    return c.doFinal(plainText);
}
References
Recipe
id: scw:crypto:nullcipher
version: 10
metadata:
  name: 'Data Protection - Secure Data Storage: Avoid data exposure: Use Cipher instead of NullCipher'
  shortDescription: Could lead to data exposure
  level: error
  language: java
  newCodeOnly: false
  scwCategory: broken_cryptography:use_of_insecuredeprecated_alogirthms
  enabled: true
  descriptionFile: Java/Crypto/descriptions/Use_cipher_over_nullcipher.html
  tags: security;basic protection set
search:
  instanceCreation:
    type: javax.crypto.NullCipher
availableFixes:
- name: Use Cipher with the recommended parameters
  actions:
  - rewrite:
      to: javax.crypto.Cipher.getInstance("AES/GCM/NoPadding")
  - modifyAssignedVariable:
      type: javax.crypto.Cipher