source: ccr/trunk/nhin-vista/projects/NHINC/Current/Product/Production/Common/NhincLib/src/gov/hhs/fha/nhinc/util/hash/SHA1HashCode.java@ 507

Last change on this file since 507 was 507, checked in by George Lilly, 15 years ago

NHIN gateway and adaptor for use on linux with VistA EHR and RPMS

File size: 2.0 KB
Line 
1package gov.hhs.fha.nhinc.util.hash;
2
3import java.io.UnsupportedEncodingException;
4import java.security.MessageDigest;
5import 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 */
12public 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}
Note: See TracBrowser for help on using the repository browser.