AES Encryption with Base64 encoding
We start by adding our imports.
1import java.nio.charset.StandardCharsets
2import java.security.Key
3import java.util.Base64
4import javax.crypto.Cipher
5import javax.crypto.spec.SecretKeySpec
For this example we’re going to use the CBC (Cipher Block Chaining) variation of AES.
1val Algorithm: String = "AES"
2val Transformation: String = "AES/ECB/PKCS5Padding"
3
4def aeskey: String => Key = key =>
5 new SecretKeySpec(key.getBytes, Algorithm)
Our encrypt
function receives a key and some text to encrypt. The function will return a base64-encoded string if everything goes ok.
1def encrypt: (String, String) => String = (key, text) =>
2 encode(_encrypt(aeskey(key), text))
3
4def _encrypt: (Key, String) => Array[Byte] = (key, text) => {
5 val cipher: Cipher = Cipher.getInstance(Transformation)
6 cipher.init(Cipher.ENCRYPT_MODE, key)
7 cipher.doFinal(text.getBytes(StandardCharsets.UTF_8))
8}
9
10def encode: Array[Byte] => String =
11 Base64.getEncoder.encodeToString
Similar to our encrypt function, decrypt
receives a key and some encrypted/base64-encoded text. The function will return a string if everything goes ok.
1def decrypt: (String, String) => String = (key, text) =>
2 _decrypt(aeskey(key), decode(text))
3
4def _decrypt: (Key, Array[Byte]) => String = (key, bytes) => {
5 val cipher: Cipher = Cipher.getInstance(Transformation)
6 cipher.init(Cipher.DECRYPT_MODE, key)
7 new String(cipher.doFinal(bytes), StandardCharsets.UTF_8)
8}
9
10def decode: String => Array[Byte] =
11 Base64.getDecoder.decode
And it is time to test it.
1val key = "w!z%C*F-JaNdRgUkXp2r5u8x/A?D(G+K" // random AES 256-bit
2val text = "some random text to encrypt"
3val enc = encrypt(key, text)
4val dec = decrypt(key, enc)
5assert(dec == text)
It’s important to catch the exceptions since various things can go wrong while executing any of these functions. For example, using different keys for encryption/decryption can raise the following exception:
Given final block not properly padded. Such issues can arise if a bad key is used during decryption.
Happy coding.
References
- Baeldung. Java AES Encryption and Decryption.
- StackOverflow. Java AES encryption and decryption.