在涉及到密码存储问题上,应该加密/生成密码摘要存储,而不是存储明文密码。比如之前的600w csdn账号泄露对用户可能造成很大损失,因此应加密/生成不可逆的摘要方式存储。 5.1 编码/解码 Shiro提供了base64和16进制字符串编码/解码的API支持,方便一些编码 ...
在涉及到密码存储问题上,应该加密/生成密码摘要存储,而不是存储明文密码。比如之前的600w csdn账号泄露对用户可能造成很大损失,因此应加密/生成不可逆的摘要方式存储。
5.1 编码/解码
Shiro提供了base64和16进制字符串编码/解码的API支持,方便一些编码解码操作。Shiro内部的一些数据的存储/表示都使用了base64和16进制字符串。
Java代码
- String str = "hello";
- String base64Encoded = Base64.encodeToString(str.getBytes());
- String str2 = Base64.decodeToString(base64Encoded);
- Assert.assertEquals(str, str2);
- String str = "hello";
- String base64Encoded = Hex.encodeToString(str.getBytes());
- String str2 = new String(Hex.decode(base64Encoded.getBytes()));
- Assert.assertEquals(str, str2);
- String str = "hello";
- String salt = "123";
- String md5 = new Md5Hash(str, salt).toString();//还可以转换为 toBase64()/toHex()
- String str = "hello";
- String salt = "123";
- String sha1 = new Sha256Hash(str, salt).toString();
- String str = "hello";
- String salt = "123";
- //内部使用MessageDigest
- String simpleHash = new SimpleHash("SHA-1", str, salt).toString();
- DefaultHashService hashService = new DefaultHashService(); //默认算法SHA-512
- hashService.setHashAlgorithmName("SHA-512");
- hashService.setPrivateSalt(new SimpleByteSource("123")); //私盐,默认无
- hashService.setGeneratePublicSalt(true);//是否生成公盐,默认false
- hashService.setRandomNumberGenerator(new SecureRandomNumberGenerator());//用于生成公盐。默认就这个
- hashService.setHashIterations(1); //生成Hash值的迭代次数
-
- HashRequest request = new HashRequest.Builder()
- .setAlgorithmName("MD5").setSource(ByteSource.Util.bytes("hello"))
- .setSalt(ByteSource.Util.bytes("123")).setIterations(2).build();
- String hex = hashService.computeHash(request).toHex();
- SecureRandomNumberGenerator randomNumberGenerator =
- new SecureRandomNumberGenerator();
- randomNumberGenerator.setSeed("123".getBytes());
- String hex = randomNumberGenerator.nextBytes().toHex();
- AesCipherService aesCipherService = new AesCipherService();
- aesCipherService.setKeySize(128); //设置key长度
- //生成key
- Key key = aesCipherService.generateNewKey();
- String text = "hello";
- //加密
- String encrptText =
- aesCipherService.encrypt(text.getBytes(), key.getEncoded()).toHex();
- //解密
- String text2 =
- new String(aesCipherService.decrypt(Hex.decode(encrptText), key.getEncoded()).getBytes());
-
- Assert.assertEquals(text, text2);
- public interface PasswordService {
- //输入明文密码得到密文密码
- String encryptPassword(Object plaintextPassword) throws IllegalArgumentException;
- }
- public interface CredentialsMatcher {
- //匹配用户输入的token的凭证(未加密)与系统提供的凭证(已加密)
- boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info);
- }
- public class MyRealm extends AuthorizingRealm {
- private PasswordService passwordService;
- public void setPasswordService(PasswordService passwordService) {
- this.passwordService = passwordService;
- }
- //省略doGetAuthorizationInfo,具体看代码
- @Override
- protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
- return new SimpleAuthenticationInfo(
- "wu",
- passwordService.encryptPassword("123"),
- getName());
- }
- }
- [main]
- passwordService=org.apache.shiro.authc.credential.DefaultPasswordService
- hashService=org.apache.shiro.crypto.hash.DefaultHashService
- passwordService.hashService=$hashService
- hashFormat=org.apache.shiro.crypto.hash.format.Shiro1CryptFormat
- passwordService.hashFormat=$hashFormat
- hashFormatFactory=org.apache.shiro.crypto.hash.format.DefaultHashFormatFactory
- passwordService.hashFormatFactory=$hashFormatFactory
-
- passwordMatcher=org.apache.shiro.authc.credential.PasswordMatcher
- passwordMatcher.passwordService=$passwordService
-
- myRealm=com.github.zhangkaitao.shiro.chapter5.hash.realm.MyRealm
- myRealm.passwordService=$passwordService
- myRealm.credentialsMatcher=$passwordMatcher
- securityManager.realms=$myRealm
- String algorithmName = "md5";
- String username = "liu";
- String password = "123";
- String salt1 = username;
- String salt2 = new SecureRandomNumberGenerator().nextBytes().toHex();
- int hashIterations = 2;
-
- SimpleHash hash = new SimpleHash(algorithmName, password, salt1 + salt2, hashIterations);
- String encodedPassword = hash.toHex();
- protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
- String username = "liu"; //用户名及salt1
- String password = "202cb962ac59075b964b07152d234b70"; //加密后的密码
- String salt2 = "202cb962ac59075b964b07152d234b70";
- SimpleAuthenticationInfo ai =
- new SimpleAuthenticationInfo(username, password, getName());
- ai.setCredentialsSalt(ByteSource.Util.bytes(username+salt2)); //盐是用户名+随机数
- return ai;
- }
- jdbcRealm.saltStyle=COLUMN
- jdbcRealm.authenticationQuery=select password, concat(username,password_salt) from users where username = ?
- jdbcRealm.credentialsMatcher=$credentialsMatcher
- [main]
- credentialsMatcher=org.apache.shiro.authc.credential.HashedCredentialsMatcher
- credentialsMatcher.hashAlgorithmName=md5
- credentialsMatcher.hashIterations=2
- credentialsMatcher.storedCredentialsHexEncoded=true
- myRealm=com.github.zhangkaitao.shiro.chapter5.hash.realm.MyRealm2
- myRealm.credentialsMatcher=$credentialsMatcher
- securityManager.realms=$myRealm
- 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;
- }
海外公司注册、海外银行开户、跨境平台代入驻、VAT、EPR等知识和在线办理:https://www.xlkjsw.com
原标题:第五章 编码/加密——《跟我学Shiro》
关键词:Shiro
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们:
admin#shaoqun.com
(#换成@)。