对字符串签名后,1:长字符串变为32位字符:aacfbe08d042fddd8ee778b148efc923 2 : 只要长字符串内容不变,签名后得到的32位字符不变。适合用来做ID等。 private String genKeyId(String keyStr) { return Md5Utils.getStringMD5(keyStr); }
Md5Utils 类如下:
1import java.io.File; 2import java.io.FileInputStream; 3import java.io.IOException; 4import java.io.InputStream; 5import java.security.MessageDigest; 6import java.security.NoSuchAlgorithmException; 7import org.apache.commons.lang3.StringUtils; 8 9public class Md5Utils { 10 protected static char[] hexDigits = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; 11 protected static MessageDigest messagedigest = null; 12 13 public Md5Utils() { } 14 static { 15 try { 16 messagedigest = MessageDigest.getInstance("MD5"); 17 } catch (NoSuchAlgorithmException var1) { 18 var1.printStackTrace(); 19 } 20 21 } 22 23 public static String getFileMD5String(File file) throws IOException { 24 InputStream fis = new FileInputStream(file); 25 byte[] buffer = new byte[1024]; 26 boolean var3 = false; 27 28 int numRead; 29 while((numRead = fis.read(buffer)) > 0) { 30 messagedigest.update(buffer, 0, numRead); 31 } 32 33 fis.close(); 34 return bufferToHex(messagedigest.digest()); 35 } 36 37 public static String getStringMD5(String str) { 38 if (StringUtils.isEmpty(str)) { 39 return ""; 40 } else { 41 byte[] buffer = str.getBytes(); 42 messagedigest.update(buffer); 43 return bufferToHex(messagedigest.digest()); 44 } 45 } 46 47 public static String bufferToHex(byte[] bytes) { 48 return bufferToHex(bytes, 0, bytes.length); 49 } 50 51 private static String bufferToHex(byte[] bytes, int m, int n) { 52 StringBuffer stringbuffer = new StringBuffer(2 * n); 53 int k = m + n; 54 55 for(int l = m; l < k; ++l) { 56 appendHexPair(bytes[l], stringbuffer); 57 } 58 59 return stringbuffer.toString(); 60 } 61 62 private static void appendHexPair(byte bt, StringBuffer stringbuffer) { 63 char c0 = hexDigits[(bt & 240) >> 4]; 64 char c1 = hexDigits[bt & 15]; 65 stringbuffer.append(c0); 66 stringbuffer.append(c1); 67 } 68 69 private static final String toHex(byte[] hash) { 70 if (hash == null) { 71 return null; 72 } else { 73 StringBuffer buf = new StringBuffer(hash.length * 2); 74 75 for(int i = 0; i < hash.length; ++i) { 76 if ((hash[i] & 255) < 16) { 77 buf.append("0"); 78 } 79 80 buf.append(Long.toString((long)(hash[i] & 255), 16)); 81 } 82 83 return buf.toString(); 84 } 85 } 86 87 public static String hash(String s) { 88 try { 89 return new String(toHex(getStringMD5(s).getBytes("UTF-8")).getBytes("UTF-8"), "UTF-8"); 90 } catch (Exception var2) { 91 return s; 92 } 93 } 94 95 public static void main(String[] args) { 96 System.out.println(getStringMD5("admin123")); 97 System.out.println(hash("123456")); 98 } 99 100 101}
