Created
May 30, 2011 23:56
-
-
Save gnrfan/999648 to your computer and use it in GitHub Desktop.
Java Snippet: Calculate SHA-1 hash of a string
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
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