Skip to content

Instantly share code, notes, and snippets.

@krishnact
Last active June 12, 2019 02:03
Show Gist options
  • Save krishnact/04e126901aa9bef8c70ef1f273a5cb6d to your computer and use it in GitHub Desktop.
Save krishnact/04e126901aa9bef8c70ef1f273a5cb6d to your computer and use it in GitHub Desktop.
Groovy Symmetric Key Encryption/Decryption
String encrypt_decrypt(String data, String symmKey, int encOrDec) {
String ALGO = "AES";
javax.crypto.spec.SecretKeySpec key = new javax.crypto.spec.SecretKeySpec(symmKey.md5().toString().decodeHex(), ALGO);
javax.crypto.Cipher c = javax.crypto.Cipher.getInstance(ALGO);
String retVal = "";
if (encOrDec == 1) {
c.init(javax.crypto.Cipher.ENCRYPT_MODE, key);
byte[] encVal = c.doFinal(data.getBytes("UTF-8"));
retVal= new String(encVal.encodeHex().toString());
}else if (encOrDec == 2) {
c.init(javax.crypto.Cipher.DECRYPT_MODE, key);
byte[] decVal = c.doFinal(data.decodeHex());
retVal= new String(decVal,"UTF-8");
}
return retVal;
}
//String enc = encrypt_decrypt("Hello","123",1);
//String dec = encrypt_decrypt(enc,"123",2);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment