 |
Subscribe to this site |
|
Groovy AES encryption decryption with Static Key and IV

Published 2 months ago
by
Chetan
import javax.crypto.Cipher
import java.security.Key
import javax.crypto.spec.IvParameterSpec
import java.security.SecureRandom
import javax.crypto.spec.SecretKeySpec
String encryptionKey = "WhatIsSecureForYourPasswordEnter"//Paste your key here
Key key = new SecretKeySpec(encryptionKey.getBytes("UTF-8"), "AES")
String s1 = "a1eb9a28501f7bea" //Paster your IV here
byte[] bytes = s1.getBytes()
IvParameterSpec iv = new IvParameterSpec(bytes)
String text = 'Test123' //Paste your plain text here
def encrypt(String text, Key key, IvParameterSpec iv) {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding")
cipher.init(Cipher.ENCRYPT_MODE, key, iv)
String encryptedStr = cipher.doFinal(text.getBytes("UTF-8")).encodeBase64()
//String encryptedStr = cipher.doFinal(text.getBytes("UTF-8")).encodeHex()
return encryptedStr
}
def decrypt(String encryptedStr, Key key, IvParameterSpec iv) {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding")
cipher.init(Cipher.DECRYPT_MODE, key, iv)
//byte[] plainText = cipher.doFinal(Base64.getDecoder().decode(encryptedStr))
byte[] plainText = cipher.doFinal(Base64.getDecoder().decode(encryptedStr))
return plainText
}
encrypted = encrypt(text, key, iv)
println "Encrypted text : ${new String(encrypted)}"
decrypted = decrypt(encrypted, key, iv)
println "Decrypted text : ${new String(decrypted)}"