Skip to content

Instantly share code, notes, and snippets.

@doridori
Last active September 14, 2023 14:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save doridori/2ce511580419cdcec7ec2ef886e91e4f to your computer and use it in GitHub Desktop.
Save doridori/2ce511580419cdcec7ec2ef886e91e4f to your computer and use it in GitHub Desktop.
Beware of the default IV blog post example
public byte[] encrypt(byte[] in)
{
...
byte[] iv = new byte[IV_LENGTH];
new SecureRandom().nextBytes(iv);
cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(iv));
byte[] cipherBytes = cipher.doFinal(s.getBytes("UTF-8"));
return concat(iv, cipherBytes);
}
public byte[] decrypt(byte[] in) throws SecurityException
{
...
cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(bytes, 0, IV_LENGTH));
return new cipher.doFinal(bytes, IV_LENGTH, bytes.length-IV_LENGTH);
}
byte[] key = new byte[16];
new SecureRandom().nextBytes(key);
SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding", "AndroidOpenSSL");
cipher.init(Cipher.ENCRYPT_MODE, keySpec);
byte[] cipherBytes = cipher.doFinal(s.getBytes("UTF-8"));
byte[] iv = cipher.getIV();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment