Base64 encode and decode in Scala

import java.util.Base64
import java.nio.charset.StandardCharsets

val plainText: String = "abcdefg"

val encoded: String = Base64.getEncoder.encodeToString(plainText.getBytes("UTF-8"))

val decoded: Array[Byte] = Base64.getDecoder.decode(encoded)

val str1 = new String(decoded)
val str2 = new String(decoded, StandardCharsets.UTF_8)

output

plainText: String = abcdefg
encoded: String = YWJjZGVmZw==
decoded: Array[Byte] = Array(97, 98, 99, 100, 101, 102, 103)
str1: String = abcdefg
str2: String = abcdefg

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)

Scala – Convert Base64 to Hex String

import java.util.Base64
import org.apache.commons.codec.binary.Hex

val guid: String = "YxRfXk827kPgkmMUX15PNg=="
val decoded: Array[Byte] = Base64.getDecoder.decode(guid)
val hexString: String = Hex.encodeHexString(decoded)

output

guid: String = YxRfXk827kPgkmMUX15PNg==
decoded: Array[Byte] = Array(99, 20, 95, 94, 79, 54, -18, 67, -32, -110, 99, 20, 95, 94, 79, 54)
hexString: String = 63145f5e4f36ee43e09263145f5e4f36