1 13 package info.magnolia.cms.security; 14 15 import java.security.MessageDigest ; 16 import java.security.NoSuchAlgorithmException ; 17 18 import org.slf4j.Logger; 19 import org.slf4j.LoggerFactory; 20 21 22 27 public final class Digester { 28 29 32 public static final String SHA1 = "SHA-1"; 34 public static final String MD5 = "MD5"; 36 40 public static final String SHA256 = "SHA-256"; 42 public static final String SHA384 = "SHA-384"; 44 public static final String SHA512 = "SHA-512"; 46 private static Logger log = LoggerFactory.getLogger(Digester.class); 47 48 51 private Digester() { 52 } 54 55 68 public static String getDigest(String data, String algorithm) throws NoSuchAlgorithmException { 69 MessageDigest md = MessageDigest.getInstance(algorithm); 70 md.reset(); 71 return new String (md.digest(data.getBytes())); 72 } 73 74 87 public static byte[] getDigest(byte[] data, String algorithm) throws NoSuchAlgorithmException { 88 MessageDigest md = MessageDigest.getInstance(algorithm); 89 md.reset(); 90 return md.digest(data); 91 } 92 93 98 public static String getSHA1Hex(String data) { 99 try { 100 String result = Digester.getDigest(data, Digester.SHA1); 101 return Digester.toHEX(result); 102 } 103 catch (NoSuchAlgorithmException e) { 104 log.error(e.getMessage(), e); 105 } 106 return data; 107 } 108 109 114 public static String getMD5Hex(String data) { 115 try { 116 String result = Digester.getDigest(data, Digester.MD5); 117 return Digester.toHEX(result); 118 } 119 catch (NoSuchAlgorithmException e) { 120 log.error(e.getMessage(), e); 121 } 122 return data; 123 } 124 125 132 public static String toHEX(String data) { 133 return Digester.toHEX(data.getBytes()); 134 } 135 136 143 public static String toHEX(byte[] data) { 144 StringBuffer hexValue = new StringBuffer (); 145 char[] digits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; 146 for (int i = 0; i < data.length; i++) { 147 byte byteValue = data[i]; 148 hexValue.append(digits[(byteValue & 0xf0) >> 4]); 149 hexValue.append(digits[byteValue & 0x0f]); 150 } 151 return hexValue.toString(); 152 } 153 } 154 | Popular Tags |