Skip to content

Instantly share code, notes, and snippets.

@gnrfan
Created May 30, 2011 23:56
Show Gist options
  • Save gnrfan/999648 to your computer and use it in GitHub Desktop.
Save gnrfan/999648 to your computer and use it in GitHub Desktop.
Java Snippet: Calculate SHA-1 hash of a string
import java.security.MessageDigest;
class SHA1Hash {
public static String getHexDigest(String str) throws java.security.NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance("SHA-1");
return byteArrayToHex(md.digest(str.getBytes()));
}
public static String byteArrayToHex(byte[] bytes) {
String result = "";
for (int i = 0; i < bytes.length; i++) {
result += Integer.toString( ( bytes[i] & 0xff ) + 0x100, 16).substring( 1 );
}
return result;
}
}
public class SHA1HashTest {
public static void main(String args[]) throws Exception {
System.out.println(SHA1Hash.getHexDigest("Hello World!"));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment