Groovy web console

subscribe to the feed Subscribe
to this
site

AES crypto

Published 5 months ago by Josatt22 with tags AES
Actions Execute script  ▶ Edit in console Back to console Show/hide line numbers View recent scripts
import javax.crypto.spec.SecretKeySpec;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.Cipher

def encrypt (def plainText, def secret) {
  println "Encrypting: ${plainText}"
    def cipher = Cipher.getInstance("AES/CBC/PKCS5Padding", "SunJCE")
    SecretKeySpec key = new SecretKeySpec(secret.getBytes("UTF-8"), "AES")
    def IVKey = Long.toUnsignedString(new Random().nextLong(), 16).toUpperCase()
    IvParameterSpec iv = new IvParameterSpec(IVKey.getBytes("UTF-8"))
    cipher.init(Cipher.ENCRYPT_MODE, key, iv)
    def result = cipher.doFinal(plainText.getBytes("UTF-8")).encodeBase64().toString()
    def ivString = cipher.getIV()
    ivString = new String(ivString, "UTF-8")
    return ivString+result
    }

def decrypt (def cypherText, def secret) {
  println "Decrypting: ${cypherText}"
  def iv = cypherText.take(16)
  byte[] decodedBytes = cypherText.drop(16).decodeBase64()
  def cipher = Cipher.getInstance("AES/CBC/PKCS5Padding", "SunJCE")
  SecretKeySpec key = new SecretKeySpec(secret.getBytes("UTF-8"), "AES")
  cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv.getBytes("UTF-8")))
  return new String(cipher.doFinal(decodedBytes), "UTF-8")
}

//demo sample
String secretKey = "DGGcYZaDQNF3x2uP";
String plainTextVal="MyPassword#1?"
String encryptedVal=encrypt(plainTextVal, secretKey) 
println "Encrypted value is "+ encryptedVal
println "Decrypted value is "+decrypt(encryptedVal, secretKey)