Shiro 提供了用于加密密码和验证密码服务的 CredentialsMatcher 接口,而 HashedCredentialsMatcher 正是 CredentialsMatcher 的一个实现类。写项目的话,总归会用到用户密码的非对称加密,目前主流的非对称加密方式是 SHA,以及在 SHA上的加盐处理,而 HashedCredentialsMatcher 也允许我们指定自己的算法和盐。
ShiroConfig配置文件:
@Bean public HashedCredentialsMatcher hashedCredentialsMatcher() { HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher(); //加密方式 hashedCredentialsMatcher.setHashAlgorithmName("SHA-512"); //加密次数 hashedCredentialsMatcher.setHashIterations(2); //存储散列后的密码是否为16进制 //hashedCredentialsMatcher.isStoredCredentialsHexEncoded(); return hashedCredentialsMatcher; }
ShiroRealm:
@Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { System.out.println("=================执行认证逻辑==================="); // 编写 Shiro 的判断逻辑 , 判断用户名和密码 // 从数据库中查询到用户名和密码 // 获取controller 传过来的 token UsernamePasswordToken tokens = (UsernamePasswordToken) token; User user = userService.selectByUsername(tokens.getUsername()); if (user == null) { throw new UnknownAccountException();//没找到帐号 } if (user.getIsValid() == 0) { throw new LockedAccountException(); //帐号无效 } // 这样通过配置中的 HashedCredentialsMatcher 进行自动校验 return new SimpleAuthenticationInfo(user, user.getPassword(), ByteSource.Util.bytes(user.getSalt()), getName());// 参数分别为:
ShiroUtils生成非对称密码:
import org.apache.commons.lang3.RandomStringUtils; import org.apache.shiro.crypto.hash.SimpleHash; public class ShiroUtils { /** * PWD_SALT_LENGTH: 密码加密盐值长度 */ public static final int PWD_SALT_LENGTH = 6; /** * PWD_ALGORITHM_NAME: 密码加密算法 */ public static final String PWD_ALGORITHM_NAME = "SHA-512"; /** * PWD_ALGORITHM_NAME: 密码加密次数 */ public static final int PWD_HASH_ITERATIONS = 2; /** * 生成密码<br/> * * @param pwd * @param salt * @return */ public static String generatePwdEncrypt(String pwd, String salt) { SimpleHash hash = new SimpleHash(PWD_ALGORITHM_NAME, pwd, salt, PWD_HASH_ITERATIONS); return hash.toString(); } /** * 生成盐值<br/> * * @return */ public static String generateSalt() { return RandomStringUtils.randomAlphabetic(PWD_SALT_LENGTH); } public static void main(String[] args) { String generateSalt = generateSalt(); String generatePwdEncrypt = generatePwdEncrypt("123456", generateSalt); System.out.println(generateSalt); System.out.println(generatePwdEncrypt); } }
来源:https://www.cnblogs.com/chong-zuo3322/p/12447729.html