文章目录
- 前言
- 一、密码工具类PasswordUtils
- 二、密码编码类PasswordEncoder
- 三、测试类
前言
一、密码工具类PasswordUtils
package com.feng.utils;import java.util.UUID;
public class PasswordUtils {public static boolean matches(String salt, String rawPass, String encPass) {return new PasswordEncoder(salt).matches(encPass, rawPass);}public static String encode(String rawPass, String salt) {return new PasswordEncoder(salt).encode(rawPass);}public static String getSalt() {return UUID.randomUUID().toString().replaceAll("-", "").substring(0, 20);}
}
二、密码编码类PasswordEncoder
package com.feng.utils;import java.security.MessageDigest;
public class PasswordEncoder {private final static String[] hexDigits &#61; { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d","e", "f" };private final static String MD5 &#61; "MD5";private final static String SHA &#61; "SHA";private Object salt;private String algorithm;public PasswordEncoder(Object salt) {this(salt, MD5);}public PasswordEncoder(Object salt, String algorithm) {this.salt &#61; salt;this.algorithm &#61; algorithm;}public String encode(String rawPass) {String result &#61; null;try {MessageDigest md &#61; MessageDigest.getInstance(algorithm);result &#61; byteArrayToHexString(md.digest(mergePasswordAndSalt(rawPass).getBytes("utf-8")));} catch (Exception ex) {}return result;}public boolean matches(String encPass, String rawPass) {String pass1 &#61; "" &#43; encPass;String pass2 &#61; encode(rawPass);return pass1.equals(pass2);}private String mergePasswordAndSalt(String password) {if (password &#61;&#61; null) {password &#61; "";}if ((salt &#61;&#61; null) || "".equals(salt)) {return password;} else {return password &#43; "{" &#43; salt.toString() &#43; "}";}}private String byteArrayToHexString(byte[] b) {StringBuffer resultSb &#61; new StringBuffer();for (int i &#61; 0; i < b.length; i&#43;&#43;) {resultSb.append(byteToHexString(b[i]));}return resultSb.toString();}private static String byteToHexString(byte b) {int n &#61; b;if (n < 0)n &#61; 256 &#43; n;int d1 &#61; n / 16;int d2 &#61; n % 16;return hexDigits[d1] &#43; hexDigits[d2];}public static void main(String[] args) {}
}
三、测试类
public static void main(String[] args) {String salt &#61; PasswordUtils.getSalt();System.out.println("salt:"&#43; salt); salt &#61; "8f5ca7b51f2a4e00b666";String password &#61; PasswordUtils.encode("666666", salt);System.out.println(password); boolean matches &#61; PasswordUtils.matches(salt, "666666", password);System.out.println(matches); }
也就是说获取salt 盐&#xff0c;拿着盐值加密密码 666666&#xff0c;盐值肯定是和密码保存起来的。
密码验证时&#xff0c;就是拿着用户输入的密码&#xff0c;与盐值加密&#xff0c;加密后的数据与 密文进行比较
如果成功&#xff0c;则密码正确。
不成功&#xff0c;则密码不正确。