2

While using Javax.crypto ciphers (more specific AES128/CBC/PKCS5Padding), the doFinal throws a NullPointerException when passing null to it as method args.

Is there a way to encrypt null so that when persisting it to the database, I don't store null as null or something similar?

e-sushi
  • 13,786
  • 10
  • 38
  • 57

2 Answers2

4

No, you can't encrypt NULL... encryption requires an input value (which NULL is not). If you absolutely must store an encrypted value in your database, you could check whether the value being encrypted is NULL and cast it to an representative value (empty string, 0, whatever your preference), and upon decryption perform a similar check for that value, and recast back to NULL. However, in my opinion, this is hacky and should be avoided - it's better not to store any value at all, but I don't know your circumstances.

hunter
  • 872
  • 10
  • 26
0

Check for null before attempting to encrypt. If it's null, don't encrypt it. Likewise for decryption.

Maybe_Factor
  • 370
  • 3
  • 10