View Javadoc

1   /**
2    * Copyright 2011-2013 The Kuali Foundation Licensed under the Educational
3    * Community License, Version 2.0 (the "License"); you may not use this file
4    * except in compliance with the License. You may obtain a copy of the License
5    * at
6    *
7    * http://www.osedu.org/licenses/ECL-2.0
8    *
9    * Unless required by applicable law or agreed to in writing, software
10   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12   * License for the specific language governing permissions and limitations under
13   * the License.
14   */
15  package org.kuali.mobility.util;
16  
17  import java.io.UnsupportedEncodingException;
18  import java.security.MessageDigest;
19  import java.security.NoSuchAlgorithmException;
20  import org.apache.commons.codec.binary.Base64;
21  import org.apache.commons.codec.binary.Hex;
22  
23  /**
24   *
25   * @author Joe Swanson <joseswan@umich.edu>
26   */
27  public class DigestUtil {
28  
29  	public static byte[] MD5(String text) throws NoSuchAlgorithmException,
30  			UnsupportedEncodingException {
31  		MessageDigest md;
32  		md = MessageDigest.getInstance("MD5");
33  		byte[] md5hash = new byte[32];
34  		md.update(text.getBytes());
35  		md5hash = md.digest();
36  		return md5hash;
37  	}
38  
39  	public static String getMD5(String text)
40  	{
41  		return getHexEncodedHash(text);
42  	}
43  
44  	public static String getBase64EncodedHash(final String text)
45  	{
46  		String ret = null;
47  		try
48  		{
49  			byte[] encodedDigest = Base64.encodeBase64(MD5(text));
50  			ret = new String(encodedDigest);
51  		}
52  		catch (NoSuchAlgorithmException nsae)
53  		{
54  			ret = "Error";
55  		}
56  		catch (UnsupportedEncodingException uee)
57  		{
58  			ret = "Error";
59  		}
60  		return ret;
61  	}
62  
63  	public static String getHexEncodedHash(final String text)
64  	{
65  		String ret = null;
66  		try
67  		{
68  			char[] encodedDigest = Hex.encodeHex(MD5(text));
69  			ret = new String(encodedDigest);
70  		}
71  		catch (NoSuchAlgorithmException nsae)
72  		{
73  			ret = "Error";
74  		}
75  		catch (UnsupportedEncodingException uee)
76  		{
77  			ret = "Error";
78  		}
79  		return ret;
80  	}
81  }