认证为了保证密码的相对安全需要对密码进行加密处理了,加密的方式有很多最常使用MD5加密,加盐
MD5特点:不可逆
public static void main(String[] args) { //md5+salt+hash Md5Hash md5Hash = new Md5Hash("123","salt",1024); System.out.println(md5Hash); //实例化securityManager DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager(); //实例化Realm ShiroMD5Realm shiroRealm = new ShiroMD5Realm(); //实例化HashedCredentialsMatcher,指定密码加密算法 HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher(); //指定加密算法 credentialsMatcher.setHashAlgorithmName("md5"); //hash散列次数 credentialsMatcher.setHashIterations(1024); shiroRealm.setCredentialsMatcher(credentialsMatcher); // 配置 SecurityManager,并注入 shiroRealm securityManager.setRealm(shiroRealm); //指定SecurityUtils中securityManager SecurityUtils.setSecurityManager(securityManager); //获取subject对象 Subject subject = SecurityUtils.getSubject(); //根据用户名和密码生成token令牌 UsernamePasswordToken token = new UsernamePasswordToken("admin","123"); try { //登录 subject.login(token); System.out.println("登录成功"); } catch (AuthenticationException e) { e.printStackTrace(); } }
认证
加盐在注册用户时,需要随机生成盐,并将盐保存在磁盘上,为认证指定对应的盐。
public class ShiroMD5Realm extends AuthorizingRealm { @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { return null; } @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { String principal = (String) token.getPrincipal(); if("admin".equals(principal)){ return new SimpleAuthenticationInfo("","9c074aff230a802bf52901cddd5c81da", ByteSource.Util.bytes("salt"),this.getName()); } return null; } }
随机盐
public class SaltUtil { /** * 生成salt * * @return */ public static String getSalt(int n) { char[] chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789~!@#$%^&*()_+".toCharArray(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < n; i++) { char aChar = chars[new Random().nextInt(chars.length)]; sb.append(aChar); } return sb.toString(); } }