Created
June 9, 2020 16:05
-
-
Save FriedEgg/f7e4c0ac96456fd1881c58b434c0e9b3 to your computer and use it in GitHub Desktop.
AES Encrpytion and Decryption functions for SAS using PROC GROOVY and Data Step Java Component Object
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
filename cp temp; | |
proc groovy classpath=cp; | |
submit parseonly; | |
import javax.crypto.spec.SecretKeySpec | |
import javax.crypto.spec.IvParameterSpec | |
import javax.crypto.Cipher | |
class GroovyCrypter { | |
def expandKey (def secret) { | |
for (def i=0; i<4; i++) { | |
secret += secret | |
} | |
return secret.substring(0, 16) | |
} | |
def process(def mode, def bytes, def secret) { | |
secret = expandKey(secret) | |
def cipher = Cipher.getInstance("AES/CBC/PKCS5Padding", "SunJCE") | |
SecretKeySpec key = new SecretKeySpec(secret.getBytes("UTF-8"), "AES") | |
cipher.init(mode, key, new IvParameterSpec(secret.getBytes("UTF-8"))) | |
return cipher.doFinal(bytes) | |
} | |
public String encrypt(String plainText, String secret) { | |
GroovyCrypter gc = new GroovyCrypter() | |
byte[] result = gc.process(Cipher.ENCRYPT_MODE, plainText.getBytes("UTF-8"), secret) | |
return result.encodeBase64().toString() | |
} | |
public String decrypt(String cypherText, String secret) { | |
GroovyCrypter gc = new GroovyCrypter() | |
byte[] result = gc.process(Cipher.DECRYPT_MODE, cypherText.decodeBase64(), secret) | |
return new String(result, "UTF-8") | |
} | |
} | |
endsubmit; | |
quit; | |
options set=classpath "%sysfunc(pathname(cp,f))"; | |
data _null_; | |
txt = "Hello Crypto!"; | |
key = "sshhhh!"; | |
declare javaObj crypter ("GroovyCrypter"); | |
length encryptedString $ 255; | |
crypter.callStringMethod("encrypt", txt, key, encryptedString); | |
length decryptedString $ 255; | |
crypter.callStringMethod("decrypt", encryptedString, key, decryptedString); | |
put (_all_) (=/); | |
run; | |
/* | |
txt=Hello Crypto! | |
key=sshhhh! | |
encryptedString=vraFtnkNjejxfdUV2KDm5w== | |
decryptedString=Hello Crypto! | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you!
Your solution is beautiful — especially when no grant on DBMS_CRYPTO :)