原文链接
http://blog.csdn.net/zhanglianhai555/article/details/47081001?utm_source=tuicool&utm_medium=referral
完整代码如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
| package com.cloudcof.cofserver.util;
import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Random;
public class MD5WithSalt { public static String generate(String password){ Random r = new Random(); StringBuilder sb = new StringBuilder(16); sb.append(r.nextInt(99999999)).append(r.nextInt(99999999)); int len = sb.length(); if(len<16){ for (int i = 0; i < 16-len; i++) { sb.append("0"); } } String salt = sb.toString(); password = md5Hex(password+salt); char[] cs = new char[48]; for(int i=0;i<48;i+=3){ cs[i] = password.charAt(i/3*2); cs[i+1] = salt.charAt(i/3); cs[i+2] = password.charAt(i/3*2+1); } return new String(cs); } public static boolean verify(String password,String md5WithSalt){ char[] md5Chars = new char[32]; char[] saltChars = new char[16]; for(int i=0;i<48;i+=3){ md5Chars[i/3*2] = md5WithSalt.charAt(i); saltChars[i/3] = md5WithSalt.charAt(i+1); md5Chars[i/3*2+1] = md5WithSalt.charAt(i+2); } String salt = new String(saltChars); return md5Hex(password+salt).equals(new String(md5Chars)); } public static String md5Hex(String src){ MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } byte[] bs = md5.digest(src.getBytes()); return new String(new Hex().encode(bs)); }
}
class Hex{ String encode(byte[] b){ String hs = ""; String stmp = ""; for (int i = 0; i < b.length; i++) { stmp = (java.lang.Integer.toHexString(b[i]&0XFF)); if (stmp.length() == 1) { hs = hs+"0"+stmp; }else{ hs = hs+stmp; } } return hs.toUpperCase(); } }
|