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 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
| import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.util.Arrays;
public class MyMD5Util { private static final String HEX_NUMS_STR="0123456789ABCDEF"; private static final Integer SALT_LENGTH = 12;
public static void main(String[] args) { String newPwd = "123456"; try{ String newPwdMd5 = MyMD5Util.getEncryptedPwd(newPwd); System.out.println(newPwdMd5); Boolean flag = MyMD5Util.validPassword("123",newPwdMd5); System.out.println(flag); }catch (Exception e){ e.printStackTrace(); } }
public static byte[] hexStringToByte(String hex) { int len = (hex.length() / 2); byte[] result = new byte[len]; char[] hexChars = hex.toCharArray(); for (int i = 0; i < len; i++) { int pos = i * 2; result[i] = (byte) (HEX_NUMS_STR.indexOf(hexChars[pos]) << 4 | HEX_NUMS_STR.indexOf(hexChars[pos + 1])); } return result; }
public static String byteToHexString(byte[] b) { StringBuffer hexString = new StringBuffer(); for (int i = 0; i < b.length; i++) { String hex = Integer.toHexString(b[i] & 0xFF); if (hex.length() == 1) { hex = '0' + hex; } hexString.append(hex.toUpperCase()); } return hexString.toString(); }
public static String getEncryptedPwd(String password) throws NoSuchAlgorithmException, UnsupportedEncodingException { byte[] pwd = null; SecureRandom random = new SecureRandom(); byte[] salt = new byte[SALT_LENGTH]; random.nextBytes(salt); MessageDigest md = null; md = MessageDigest.getInstance("MD5"); md.update(salt); md.update(password.getBytes("UTF-8")); byte[] digest = md.digest(); pwd = new byte[digest.length + SALT_LENGTH]; System.arraycopy(salt, 0, pwd, 0, SALT_LENGTH); System.arraycopy(digest, 0, pwd, SALT_LENGTH, digest.length); return byteToHexString(pwd); }
public static boolean validPassword(String password, String passwordInDb) throws NoSuchAlgorithmException, UnsupportedEncodingException { byte[] pwdInDb = hexStringToByte(passwordInDb); byte[] salt = new byte[SALT_LENGTH]; System.arraycopy(pwdInDb, 0, salt, 0, SALT_LENGTH); MessageDigest md = MessageDigest.getInstance("MD5"); md.update(salt); md.update(password.getBytes("UTF-8")); byte[] digest = md.digest(); byte[] digestInDb = new byte[pwdInDb.length - SALT_LENGTH]; System.arraycopy(pwdInDb, SALT_LENGTH, digestInDb, 0, digestInDb.length); if (Arrays.equals(digest, digestInDb)) { return true; } else { return false; } } }
|