一、散列算法
散列算法让其保证不可逆,安全。这里举一个例子sh1的摘要算法。上代码
public class HashRsaUtil {
public static final String SHA1="SHA-1";
public static final Integer ITERATIONS=512;
public static String sha1(String input, String salt){
return new SimpleHash(SHA1,input,salt,ITERATIONS).toString();
}
public static String generateSalt(){
SecureRandomNumberGenerator generator = new SecureRandomNumberGenerator();
return generator.nextBytes().toHex();
}
public static Map<String,String> encryptInscription( String inscription){
Map<String,String> map = new HashMap<>(16);
String salt = generateSalt();
String ciphertext = sha1(inscription, salt);
map.put("salt",salt);
map.put("ciphertext",ciphertext);
return map;
}
二、Remal使用散列算法
1.修改service模拟数据库出来的数据
@Override
public Map<String, String> findPasswordByName(String userName) {
return HashRsaUtil.encryptInscription("123");
}
2.修改自定义的remal
package com.example.config;
import com.example.service.impl.SecurityServiceImpl;
import com.example.untils.HashRsaUtil;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.util.StringUtils;
import java.util.Map;
public class DefinitionRealm extends AuthorizingRealm {
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
return null;
}
public DefinitionRealm(){
HashedCredentialsMatcher matcher = new HashedCredentialsMatcher(HashRsaUtil.SHA1);
matcher.setHashIterations(HashRsaUtil.ITERATIONS);
setCredentialsMatcher(matcher);
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
String principal = (String) authenticationToken.getPrincipal();
SecurityServiceImpl securityService = new SecurityServiceImpl();
Map<String, String> map = securityService.findPasswordByName(principal);
if (StringUtils.isEmpty(map)) {
throw new UnknownAccountException("该用户不存在!");
}
String salt = map.get("salt");
String password = map.get("ciphertext");
return new SimpleAuthenticationInfo(principal, password, ByteSource.Util.bytes(salt), getName());
}
}
3.测试
@Test
public void shiroLoginTest() {
IniSecurityManagerFactory factory = new IniSecurityManagerFactory("classpath:shiro.ini");
SecurityManager securityManager = factory.getInstance();
SecurityUtils.setSecurityManager(securityManager);
Subject subject = SecurityUtils.getSubject();
UsernamePasswordToken passwordToken = new UsernamePasswordToken("zhangSan", "123");
subject.login(passwordToken);
System.out.println("登录结果" + subject.isAuthenticated());
}
结果:
|