01: package org.jgroups.util;
02:
03: import java.util.*;
04: import java.io.*;
05: import java.security.*;
06:
07: /**
08: * Helper class for performing some common hashing methods
09: *
10: * @author Chris Mills
11: */
12: public class HashUtils {
13: /**
14: * Used to convert a byte array in to a java.lang.String object
15: * @param bytes the bytes to be converted
16: * @return the String representation
17: */
18: private static String getString(byte[] bytes) {
19: StringBuffer sb = new StringBuffer();
20: for (int i = 0; i < bytes.length; i++) {
21: byte b = bytes[i];
22: sb.append(0x00FF & b);
23: if (i + 1 < bytes.length) {
24: sb.append("-");
25: }
26: }
27: return sb.toString();
28: }
29:
30: /**
31: * Used to convert a java.lang.String in to a byte array
32: * @param str the String to be converted
33: * @return the byte array representation of the passed in String
34: */
35: private static byte[] getBytes(String str) {
36: ByteArrayOutputStream bos = new ByteArrayOutputStream();
37: StringTokenizer st = new StringTokenizer(str, "-", false);
38: while (st.hasMoreTokens()) {
39: int i = Integer.parseInt(st.nextToken());
40: bos.write((byte) i);
41: }
42: return bos.toByteArray();
43: }
44:
45: /**
46: * Converts a java.lang.String in to a MD5 hashed String
47: * @param source the source String
48: * @return the MD5 hashed version of the string
49: */
50: public static String md5(String source) {
51: try {
52: MessageDigest md = MessageDigest.getInstance("MD5");
53: byte[] bytes = md.digest(source.getBytes());
54: return getString(bytes);
55: } catch (Exception e) {
56: return null;
57: }
58: }
59:
60: /**
61: * Converts a java.lang.String in to a SHA hashed String
62: * @param source the source String
63: * @return the MD5 hashed version of the string
64: */
65: public static String sha(String source) {
66: try {
67: MessageDigest md = MessageDigest.getInstance("SHA");
68: byte[] bytes = md.digest(source.getBytes());
69: return getString(bytes);
70: } catch (Exception e) {
71: e.printStackTrace();
72: return null;
73: }
74: }
75: }
|