Many web applications need to generate a SHA1 hash for verifying file integrity. If you use the Apache Commons libraries, the DigestUtils class offers convenience methods for generating hashes.
If you don’t use Apache Commons, the following function will generate SHA1 hashes for you. Simply pass the string to calculate the hash from into the function ( to_be_sha1 ); the function will then return the SHA1 hash. If an error is encountered (such as the passed-in string being null), a RuntimeException will be thrown.
/**
* Calculates a SHA1 hash from a provided String. If
* to_be_sha1 is null, a RuntimeException will be thrown.
*
* @param to_be_sha1 String to calculate a SHA1 hash from.
* @return A SHA1 hash from the provided String.
*/
public static String generateSHA1(String to_be_sha1) {
String sha1_sum = "";
//if the provided String is null, throw an Exception.
if (to_be_sha1 == null) {
throw new RuntimeException("There is no String to calculate a SHA1 hash from.");
}
try {
MessageDigest digest = MessageDigest.getInstance("SHA1");
byte[] array = digest.digest(to_be_sha1.getBytes("UTF-8"));
StringBuffer collector = new StringBuffer();
for (int i = 0; i < array.length; i++) {
collector.append(Integer.toString((array[i] & 0xff) + 0x100, 16).substring(1));
}
sha1_sum = collector.toString();
}//end try
catch (NoSuchAlgorithmException e) {
throw new RuntimeException("Could not find a SHA1 instance: " + e.getMessage());
}
catch (UnsupportedEncodingException e) {
throw new RuntimeException("Could not translate UTF-8: " + e.getMessage());
}
return sha1_sum;
}//end generateSHA1
Add these imports as well:
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;