[507] | 1 | package gov.hhs.fha.nhinc.util.hash;
|
---|
| 2 |
|
---|
| 3 | import java.io.UnsupportedEncodingException;
|
---|
| 4 | import java.security.MessageDigest;
|
---|
| 5 | import java.security.NoSuchAlgorithmException;
|
---|
| 6 |
|
---|
| 7 | /**
|
---|
| 8 | * This class is used to compute the SHA1 hash code of a string.
|
---|
| 9 | *
|
---|
| 10 | * @author Les Westberg
|
---|
| 11 | */
|
---|
| 12 | public class SHA1HashCode
|
---|
| 13 | {
|
---|
| 14 |
|
---|
| 15 | /**
|
---|
| 16 | * This method takes a byte array and converts it to a String HEX representation
|
---|
| 17 | * of the byte array.
|
---|
| 18 | *
|
---|
| 19 | * @param data The byte array to be converted.
|
---|
| 20 | * @return The HEX string representation of the byte array.
|
---|
| 21 | */
|
---|
| 22 | private static String convertToHex(byte[] data)
|
---|
| 23 | {
|
---|
| 24 | StringBuffer buf = new StringBuffer();
|
---|
| 25 | for (int i = 0; i < data.length; i++)
|
---|
| 26 | {
|
---|
| 27 | int halfbyte = (data[i] >>> 4) & 0x0F;
|
---|
| 28 | int two_halfs = 0;
|
---|
| 29 | do
|
---|
| 30 | {
|
---|
| 31 | if ((0 <= halfbyte) && (halfbyte <= 9))
|
---|
| 32 | {
|
---|
| 33 | buf.append((char) ('0' + halfbyte));
|
---|
| 34 | } else
|
---|
| 35 | {
|
---|
| 36 | buf.append((char) ('a' + (halfbyte - 10)));
|
---|
| 37 | }
|
---|
| 38 | halfbyte = data[i] & 0x0F;
|
---|
| 39 | } while (two_halfs++ < 1);
|
---|
| 40 | }
|
---|
| 41 | return buf.toString();
|
---|
| 42 | }
|
---|
| 43 |
|
---|
| 44 |
|
---|
| 45 | /**
|
---|
| 46 | * This method calculates the SHA1 hash code for the given string.
|
---|
| 47 | *
|
---|
| 48 | * @param text The string that is being used to compute the SHA-1 hash code.
|
---|
| 49 | * @return The SHA-1 has code based on the given string.
|
---|
| 50 | * @throws java.security.NoSuchAlgorithmException
|
---|
| 51 | * @throws java.io.UnsupportedEncodingException
|
---|
| 52 | */
|
---|
| 53 | public static String calculateSHA1(String text)
|
---|
| 54 | throws NoSuchAlgorithmException, UnsupportedEncodingException
|
---|
| 55 | {
|
---|
| 56 | if (text != null)
|
---|
| 57 | {
|
---|
| 58 | MessageDigest md;
|
---|
| 59 | md = MessageDigest.getInstance("SHA-1");
|
---|
| 60 | byte[] sha1hash = new byte[40];
|
---|
| 61 | md.update(text.getBytes("iso-8859-1"), 0, text.length());
|
---|
| 62 | sha1hash = md.digest();
|
---|
| 63 | return convertToHex(sha1hash);
|
---|
| 64 | }
|
---|
| 65 | else
|
---|
| 66 | {
|
---|
| 67 | return "";
|
---|
| 68 | }
|
---|
| 69 | }
|
---|
| 70 | }
|
---|