SHA1 해시는 Apache commons의 DigestUtils 를 사용하여 생성 할 수 있습니다.
sha1 = org.apache.commons.codec.digest.DigestUtils.sha1Hex( value );
SHA1 해시는 jdk의 MessageDigest 클래스를 사용하여 직접 생성 할 수도 있습니다.
MessageDigest digest = MessageDigest.getInstance("SHA-1");
digest.reset();
digest.update(value.getBytes("utf8"));
sha1 = String.format("%040x", new BigInteger(1, digest.digest()));
다음은 "this is a test"문자열의 sha1을 생성하는 예제입니다. 먼저 jdk의 MessageDigest 클래스를 사용하는 메소드를 사용합니다. 그런 다음 Apache Commons의 DigestUtils 클래스를 사용합니다. 생성 된 sha1은 콘솔에 기록됩니다.
import java.math.BigInteger;
import java.security.MessageDigest;
public class SHA1 {
public static void main(String[] argv){
String value = "this is a test";
String sha1 = "";
// With the java libraries
try {
MessageDigest digest = MessageDigest.getInstance("SHA-1");
digest.reset();
digest.update(value.getBytes("utf8"));
sha1 = String.format("%040x", new BigInteger(1, digest.digest()));
} catch (Exception e){
e.printStackTrace();
}
System.out.println( "The sha1 of \""+ value + "\" is:");
System.out.println( sha1 );
System.out.println();
// With Apache commons
sha1 = org.apache.commons.codec.digest.DigestUtils.sha1Hex( value );
System.out.println( "The sha1 of \""+ value + "\" is:");
System.out.println( sha1 );
}
}
The sha1 of "this is a test" is: fa26be19de6bff93f70bc2308434e4a440bbad02 The sha1 of "this is a test" is: fa26be19de6bff93f70bc2308434e4a440bbad02