mozq

ShiroUtil 对密码进行加密

package com.mozq.sb.shiro02.config;

import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.crypto.hash.SimpleHash;

public class ShiroUtil {
    public static final String alg = "MD5";
    public static final Integer iterator = 3;
    public static final boolean hex = true;

    public static String encode(String pass){
        SimpleHash simpleHash = new SimpleHash(alg, pass, null, iterator);
        //simpleHash.setIterations(iterator);//错误,因为哈希算法是在构造器中调用,不能创建对象后再设置次数
        return hex ? simpleHash.toHex(): simpleHash.toBase64();
        /*System.out.println(Arrays.toString(simpleHash.getBytes()));
        System.out.println(simpleHash.toHex());
        System.out.println(simpleHash.toBase64());*/
    }

    public static void main(String[] args) {
        String pass = "jiechang";
        // 1.使用工具类加密密码
        String hashPass = ShiroUtil.encode(pass);
        System.out.println(hashPass);

        // 2.创建密码匹配器,注入自定义realm中
        HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher(alg);
        credentialsMatcher.setStoredCredentialsHexEncoded(hex);
        credentialsMatcher.setHashIterations(iterator);

        // 3.调用主体登录,将调用匹配方法。
        UsernamePasswordToken token = new UsernamePasswordToken("liubei", pass);
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo("liubei", hashPass, "A");
        boolean OK = credentialsMatcher.doCredentialsMatch(token, info);
        System.out.println(OK);
    }
}

分类:

技术点:

相关文章:

  • 2021-11-01
  • 2021-11-24
  • 2021-12-19
  • 2021-11-17
  • 2021-04-19
  • 2021-04-13
  • 2021-08-11
  • 2021-11-06
猜你喜欢
  • 2021-08-29
  • 2021-04-29
  • 2021-12-05
  • 2021-12-30
  • 2021-10-26
  • 2021-04-01
  • 2021-12-10
相关资源
相似解决方案