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);
}
}