avatar

Andres Jaimes

AES Encryption with Base64 encoding

By Andres Jaimes

- 2 minutes read - 276 words

We start by adding our imports.

import java.nio.charset.StandardCharsets
import java.security.Key
import java.util.Base64
import javax.crypto.Cipher
import javax.crypto.spec.SecretKeySpec

For this example we’re going to use the CBC (Cipher Block Chaining) variation of AES.

val Algorithm: String = "AES"
val Transformation: String = "AES/ECB/PKCS5Padding"

def aeskey: String => Key = key =>
  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.

def encrypt: (String, String) => String = (key, text) =>
  encode(_encrypt(aeskey(key), text))

def _encrypt: (Key, String) => Array[Byte] = (key, text) => {
  val cipher: Cipher = Cipher.getInstance(Transformation)
  cipher.init(Cipher.ENCRYPT_MODE, key)
  cipher.doFinal(text.getBytes(StandardCharsets.UTF_8))
}

def encode: Array[Byte] => String =
  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.

def decrypt: (String, String) => String = (key, text) =>
  _decrypt(aeskey(key), decode(text))

def _decrypt: (Key, Array[Byte]) => String = (key, bytes) => {
  val cipher: Cipher = Cipher.getInstance(Transformation)
  cipher.init(Cipher.DECRYPT_MODE, key)
  new String(cipher.doFinal(bytes), StandardCharsets.UTF_8)
}

def decode: String => Array[Byte] =
  Base64.getDecoder.decode

And it is time to test it.

val key = "w!z%C*F-JaNdRgUkXp2r5u8x/A?D(G+K" // random AES 256-bit
val text = "some random text to encrypt"
val enc = encrypt(key, text)
val dec = decrypt(key, enc)
assert(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