Shiro笔记(四)编码/加密

时间:2023-11-22 14:27:14

Shiro笔记(四)编码/加密

一、编码和解码

     //base64编码、解码
@Test
public void testBase64(){
String str="tang";
byte[] encode = Base64.encode(str.getBytes());
System.out.println("Encode result:"+encode);
System.out.println("The decode result:"+Base64.decodeToString(encode));
} //16进制字符串编码,解码
@Test
public void testHex(){
String str="Java";
char[] encode = Hex.encode(str.getBytes());
System.out.println("encode result:"+encode);
System.out.println("decode result:"+new String(Hex.decode(encode)));
}

二、散列算法

散列算法一般用于生成数据的摘要信息,是一种不可逆的算法,一般适合存储密码之类的数据,常见的散列算法如MD5,SHA等。

     //MD5算法
@Test
public void testMD5(){
String str="king";
String salt="salt1";
String s = new Md5Hash(str, salt).toString();
System.out.println("MD5 code: "+s);
} //SHA算法
@Test
public void testSHA(){
String str="king";
String salt="salt1";
String s = new Sha256Hash(str, salt).toString();
System.out.println("SHA code: "+s);
}

三、PasswordService/CredentialMatcher

Shiro 提供了 PasswordService 及 CredentialsMatcher 用于提供加密密码及验证密码服务。

 public interface PasswordService {

     //输入明文密码得到密文密码
String encryptPassword(Object plaintextPassword) throws IllegalArgumentException; /**
* @param submittedPlaintext a raw/plaintext password submitted by an end user/Subject.
* @param encrypted the previously encrypted password known to be associated with an account.
* This value is expected to have been previously generated from the
* {@link #encryptPassword(Object) encryptPassword} method (typically
* when the account is created or the account's password is reset).
* @return {@code true} if the {@code submittedPlaintext} password matches the existing {@code saved} password,
* {@code false} otherwise.
* @see ByteSource.Util#isCompatible(Object)
*/
boolean passwordsMatch(Object submittedPlaintext, String encrypted);
}
 public interface CredentialsMatcher {

     //匹配用户输入的 token 的凭证(未加密)与系统提供的凭证(已加密)
boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info); }

Shiro 默认提供了 PasswordService 实现 DefaultPasswordService;CredentialsMatcher 实现
PasswordMatcher 及 HashedCredentialsMatcher(更强大)。

应用实例:

 public class MyRealm extends AuthorizingRealm{

     private PasswordService passwordService;

     public void setPasswordService(PasswordService passwordService) {
this.passwordService = passwordService;
} protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
return null;
} protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
return new SimpleAuthenticationInfo("tang",
passwordService.encryptPassword("123456"),getName());
}
}

HashedCredentialsMatcher应用:

 public class MyRealm2 extends AuthorizingRealm {

     @Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
return null;
} @Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
String username = "liu"; //用户名及salt1
String salt2 = "0072273a5d87322163795118fdd7c45e";
String password = "be320beca57748ab9632c4121ccac0db"; //加密后的密码
SimpleAuthenticationInfo ai = new SimpleAuthenticationInfo(username, password, getName());
ai.setCredentialsSalt(ByteSource.Util.bytes(username+salt2)); //盐是用户名+随机数
return ai;
}
}

四、密码重试次数限制

如在 1 个小时内密码最多重试 5 次,如果尝试次数超过 5 次就锁定 1 小时,1 小时后可再
次重试,如果还是重试失败,可以锁定如 1 天,以此类推,防止密码被暴力破解。我们通
过继承 HashedCredentialsMatcher,且使用 Ehcache 记录重试次数和超时时间。

 public class RetryLimitHashedCredentialsMatcher extends HashedCredentialsMatcher {

     private Ehcache passwordRetryCache;

     public RetryLimitHashedCredentialsMatcher() {
CacheManager cacheManager = CacheManager.newInstance(CacheManager.class.getClassLoader().getResource("ehcache.xml"));
passwordRetryCache = cacheManager.getCache("passwordRetryCache");
} @Override
public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
String username = (String)token.getPrincipal();
//retry count + 1
Element element = passwordRetryCache.get(username);
if(element == null) {
element = new Element(username , new AtomicInteger(0));
passwordRetryCache.put(element);
}
AtomicInteger retryCount = (AtomicInteger)element.getObjectValue();
if(retryCount.incrementAndGet() > 5) {
//if retry count > 5 throw
throw new ExcessiveAttemptsException();
} boolean matches = super.doCredentialsMatch(token, info);
if(matches) {
//clear retry count
passwordRetryCache.remove(username);
}
return matches;
}
}
 <?xml version="1.0" encoding="UTF-8"?>
<ehcache name="es"> <diskStore path="java.io.tmpdir"/> <!-- 登录记录缓存 锁定10分钟 -->
<cache name="passwordRetryCache"
maxEntriesLocalHeap="2000"
eternal="false"
timeToIdleSeconds="3600"
timeToLiveSeconds="0"
overflowToDisk="false"
statistics="true">
</cache> </ehcache>