Java Code (Sha1.java):
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class Sha1 {
public static String text;
public static void main(String[] args) throws NoSuchAlgorithmException {
for (String item : args) {
text = item;
System.out.println("Text: " + item + " SHA1: " + getSha());
}
}
public static String getSha() throws NoSuchAlgorithmException {
byte[] digest = MessageDigest.getInstance("SHA1").digest(text.getBytes());
return new BigInteger(1, digest).toString(16);
}
}
Compile Class:
javac Sha1.java
Test Class:
java -cp . Sha1 abc abcd
Result of test:
Text: abc SHA1: a9993e364706816aba3e25717850c26c9cd0d89d
Text: abcd SHA1: 81fe8bfe87576c3ecb22426f8e57847382917acf
Launch SAS:
sas -SET CLASSPATH /path/to/class/folder
SAS Code;
data foo;
length text sha1 $40;
declare javaobj s('Sha1');
do text='abc','abcd';
s.setStaticStringField('text',text);
s.callStaticStringMethod('getSha',sha1);
put 'Text: ' text ' SHA1: ' sha1;
end;
run;
SAS Output:
Text: abc SHA1: a9993e364706816aba3e25717850c26c9cd0d89d
Text: abcd SHA1: 81fe8bfe87576c3ecb22426f8e57847382917acf
Another SAS Example, SHA1 Hash all Names in sashelp.class:
data class;
if 0 then set sashelp.class;
length sha1 $40;
declare hash c(dataset:'sashelp.class',ordered:'y');
declare hiter i('c');
c.definekey('sex','name');
c.definedata(all:'y');
c.definedone();
declare javaobj j('Sha1');
_n_=i.first();
do while(_n_=0);
j.setStaticStringField('text',name);
j.callStaticStringMethod('getSha',sha1);
output;
_n_=i.next();
end;
stop;
run;
This is somewhat a continuation of my previous postings on Ciphers and performing data masking in SAS:
Here is an update to the above utilizing PROC GROOVY
filename cp temp;
proc groovy classpath=cp;
submit parseonly;
import java.security.MessageDigest;
class Sha1 {
public String encode(String message) {
return new BigInteger(1, MessageDigest.getInstance("SHA1").digest(message.getBytes())).toString(16);
}
}
endsubmit;
quit;
options set=classpath "%sysfunc(pathname(cp,f))";
data class;
dcl javaobj sha1('Sha1');
do until (done);
set sashelp.class end=done;
length encoded_name $ 40;
sha1.callStringMethod('encode', strip(name), encoded_name);
output;
end;
run;
Are you ready for the spotlight? We're accepting content ideas for SAS Innovate 2025 to be held May 6-9 in Orlando, FL. The call is open until September 25. Read more here about why you should contribute and what is in it for you!
Learn how use the CAT functions in SAS to join values from multiple variables into a single value.
Find more tutorials on the SAS Users YouTube channel.