Scala – AES Encryption with CBC and PKCS7Padding

import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.Security;
import java.util.Base64;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Hex

val ENCRYPT_KEY = "aaaaaaaaaaaaaaaa"
val ENCRYPT_IV = "bbbbbbbbbbbbbbbb"

def encrypt(value : String) : String = {
    val plainText: String = value
    try {
        val key: Array[Byte] = ENCRYPT_KEY.getBytes("UTF-8")
        val ivs: Array[Byte] = ENCRYPT_IV.getBytes("UTF-8")
        val cipher:Cipher = Cipher.getInstance("AES/CBC/PKCS5Padding") // PKCS7Padding
        val secretKeySpec: SecretKeySpec = new SecretKeySpec(key, "AES")
        val paramSpec  = new IvParameterSpec(ivs)
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, paramSpec)
        val escapedString: String = Base64.getEncoder.encodeToString(cipher.doFinal(plainText.getBytes("UTF-8"))).trim()
        val decoded: Array[Byte] = Base64.getDecoder.decode(escapedString)
        val hexString: String = Hex.encodeHexString(decoded)
  
        return hexString;
    }
    catch {
        case e: Throwable =>println("Cannot encode "+ e)
        return value
    }  
}

val hexString = encrypt("test message");

output

hexString: String = be7dec3aba8964e18cf7a942f9a89880

validate result with The X Online Tools (the-x.cn)