@Test public void Md5Test() { // 对单个信息加密 Md5Hash md5 = new Md5Hash("123456"); System.out.println(md5.toString()); // 加密添加盐值 增大解密难度 md5 = new Md5Hash("123456","aaa"); System.out.println(md5.toString()); // 加密添加盐值 增大解密难度 2迭代两次 md5 = new Md5Hash("123456","aaa",2); System.out.println(md5); }
输出的结果:
e10adc3949ba59abbe56e057f20f883e 88316675d7882e3fdbe066000273842c a7cf41c6537065fe724cc9980f8b5635
@Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { // 获取账号信息 String principal = (String) token.getPrincipal(); // 正常逻辑此处应该根据账号去数据库中查询,此处我们默认账号为 root 密码123456 // 验证账号 if(!"root".equals(principal)){ // 账号错误 return null; } //String pwd = "123456"; // 12345 根据 盐值 aaa 加密获取的密文 //88316675d7882e3fdbe066000273842c 1次迭代的密文 //a7cf41c6537065fe724cc9980f8b5635 2次迭代的密文 String pwd = "88316675d7882e3fdbe066000273842c"; // 验证密码 AuthenticationInfo info = new SimpleAuthenticationInfo( principal, pwd,new SimpleByteSource("aaa"),"myrealm"); return info; }
[main] #定义凭证匹配器 credentialsMatcher=org.apache.shiro.authc.credential.HashedCredentialsMatcher #散列算法 credentialsMatcher.hashAlgorithmName=md5 #散列次数 credentialsMatcher.hashIterations=1 #将凭证匹配器设置到realm customRealm=com.dpb.realm.MyRealm customRealm.credentialsMatcher=$credentialsMatcher securityManager.realms=$customRealm
测试
@Test public void test() { // 1.获取SecurityManager工厂对象 Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini"); // 2.通过Factory对象获取SecurityManager对象 SecurityManager securityManager = factory.getInstance(); // 3.将SecurityManager对象添加到当前运行环境中 SecurityUtils.setSecurityManager(securityManager); // 4.获取Subject对象 Subject subject = SecurityUtils.getSubject(); AuthenticationToken token = new UsernamePasswordToken("root", "123456"); // 登录操作 try { subject.login(token); } catch (UnknownAccountException e) { System.out.println("账号出错..."); } catch(IncorrectCredentialsException e){ System.out.println("密码出错..."); } // 获取登录的状态 System.out.println(subject.isAuthenticated()); }