/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ee.tlu.htk.dippler.utils; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; /** * * @author pjotr */ public class GenerateHash { public static String generateMD5(String input) { try { MessageDigest md = MessageDigest.getInstance("MD5"); byte[] digest = md.digest(input.getBytes()); String result = hexEncode(digest); // Just a check in case we get less than 32 chars while(result.length() < 32) { result = "0" + result; } return result; } catch (NoSuchAlgorithmException e) { //throw new RuntimeException(e); System.err.println(e); } return null; } public static String generateSHA1(String input) { try { MessageDigest md = MessageDigest.getInstance("SHA-1"); byte[] digest = md.digest(input.getBytes()); return hexEncode(digest); } catch (NoSuchAlgorithmException e) { //throw new RuntimeException(e); System.err.println(e); } return null; } /** * The byte[] returned by MessageDigest does not have a nice * textual representation, so some form of encoding is usually performed. * * This implementation follows the example of David Flanagan's book * "Java In A Nutshell", and converts a byte array into a String * of hex characters. * * Another popular alternative is to use a "Base64" encoding. */ static private String hexEncode(byte[] aInput) { StringBuilder result = new StringBuilder(); char[] digits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; for (int idx = 0; idx < aInput.length; ++idx) { byte b = aInput[idx]; result.append(digits[(b & 0xf0) >> 4]); result.append(digits[b & 0x0f]); } return result.toString(); } }