Last active
September 14, 2023 14:24
-
-
Save doridori/2ce511580419cdcec7ec2ef886e91e4f to your computer and use it in GitHub Desktop.
Beware of the default IV blog post example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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