Skip to content

Instantly share code, notes, and snippets.

@scalactic
Last active June 28, 2021 17:05
Show Gist options
  • Save scalactic/7366a13e2ad10a08a23c2fcf3c4d2152 to your computer and use it in GitHub Desktop.
Save scalactic/7366a13e2ad10a08a23c2fcf3c4d2152 to your computer and use it in GitHub Desktop.
Scala encrypt decrpyt AES
import javax.crypto.{Cipher, KeyGenerator}
import javax.crypto.spec.SecretKeySpec
import java.util.Base64
val keyGenerator = KeyGenerator.getInstance("AES")
keyGenerator.init(128)
val secretKey = keyGenerator.generateKey
val encodedKey = Base64.getEncoder.encodeToString(secretKey.getEncoded)
val decodedKey = Base64.getDecoder.decode(encodedKey)
val secretKey = new SecretKeySpec(decodedKey, 0, decodedKey.length, "AES")
def createSecretKey(encodedKey:String):SecretKeySpec = {
val decodedKey = Base64.getDecoder.decode(encodedKey)
new SecretKeySpec(decodedKey, 0, decodedKey.length, "AES")
}
def encryptAES(plainText: String, secretKey: SecretKeySpec): String = {
val cipher = Cipher.getInstance("AES")
cipher.init(Cipher.ENCRYPT_MODE, secretKey)
val encryptedBytes = cipher.doFinal(plainText.getBytes)
Base64.getEncoder.encodeToString(encryptedBytes)
}
def encryptAES(plainText: String, encodedKey: String): String = {
val secretKey = createSecretKey(encodedKey)
val cipher = Cipher.getInstance("AES")
cipher.init(Cipher.ENCRYPT_MODE, secretKey)
val encryptedBytes = cipher.doFinal(plainText.getBytes)
Base64.getEncoder.encodeToString(encryptedBytes)
}
def decryptAES(encryptedText: String, secretKey: SecretKeySpec): String = {
val cipher = Cipher.getInstance("AES")
cipher.init(Cipher.DECRYPT_MODE, secretKey)
val decryptedBytes = cipher.doFinal(Base64.getDecoder.decode(encryptedText))
new String(decryptedBytes)
}
def decryptAES(encryptedText: String, encodedKey: String): String = {
val secretKey = createSecretKey(encodedKey)
val cipher = Cipher.getInstance("AES")
cipher.init(Cipher.DECRYPT_MODE, secretKey)
val decryptedBytes = cipher.doFinal(Base64.getDecoder.decode(encryptedText))
new String(decryptedBytes)
}
val encrypted = encryptAES("Hello", secretKey)
val decrypted = decryptAES(encrypted, secretKey)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment