前言
前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住分享一下给大家。点击跳转到网站,这篇文章男女通用,看懂了就去分享给你的码吧。
绝大多数网站中的用户密码使用MD5加密后保存到数据库中,如果采用弱密码,例如:123456、admin等,有太多的MD5穷举网站可以获取到密码的MD5值,这个时候我们有必要改进密码加密机制!
SimpleHash是一种常用于Java应用程序的密码加密实用程序。它是ApacheShiro安全框架的一部分,用于在将密码存储到数据库之前对其进行加密。
SimpleHash原理:
public SimpleHash(String algorithmName, Object source, Object salt, int hashIterations)
algorithmName:加密形式(具体支持哪些算法,请自行百度)
source:简单理解就是传入的原始明文密码值
salt:盐值
hashIterations:加密次数
最终得到加密的密码 = MD5(明文密码 + 盐值)* 加密次数
- 引入Shiro
- shiro
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.4.2</version>
</dependency>
public SimpleHash(String algorithmName, Object source, Object salt, int hashIterations) throws CodecException, UnknownAlgorithmException {
this.hexEncoded = null;
this.base64Encoded = null;
if (!StringUtils.hasText(algorithmName)) {
throw new NullPointerException("algorithmName argument cannot be null or empty.");
} else {
this.algorithmName = algorithmName;
this.iterations = Math.max(1, hashIterations);
ByteSource saltBytes = null;
if (salt != null) {
saltBytes = this.convertSaltToBytes(salt);
this.salt = saltBytes;
}
ByteSource sourceBytes = this.convertSourceToBytes(source);
this.hash(sourceBytes, saltBytes, hashIterations);
}
}
package org.bluedream.core.utils;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;
import org.bluedream.core.module.sys.entity.User;
public class PasswordHelper {
// 加密形式
public static final String ALGORITHM_NAME = "MD5";
// 加密次数
public static final int HASH_ITERATIONS = 128;
private PasswordHelper(){
throw new AssertionError();
}
/**
* 返回MD5加密后的字符串
* @param sourcePWD 原始密码文本
* @param salt 盐值
* @return
*/
public static String encryptPassword(String sourcePWD , String salt){
return new SimpleHash(ALGORITHM_NAME , sourcePWD , ByteSource.Util.bytes(salt) , HASH_ITERATIONS).toHex();
}
/**
* User对象加密
* @param user
* @return
*/
public static String encryptPassword(User user){
return encryptPassword(user.getPassword() , user.getLoginCode());
}
/**
* test return new password
* @param args
*/
public static void main(String[] args) {
String pwd = "123456";
String salt = "system";
System.out.println(encryptPassword(pwd , salt));
}
}
##SimpleHash的工作原理
SimpleHash使用salt和散列算法的组合来加密密码。salt是一个随机字符串,在对其进行哈希之前会添加到密码中。这使得攻击者更难使用字典攻击或彩虹表来破解密码。
SimpleHash使用的哈希算法是可配置的,可以设置为使用各种不同的算法,包括MD5、SHA-1、SHA-256和SHA-512。SimpleHash使用的默认算法是SHA-256。
##在应用程序中使用SimpleHash
要在Java应用程序中使用SimpleHash,您需要将ApacheShiro依赖项添加到项目中。完成此操作后,您可以创建一个SimpleHash对象并使用它来加密密码。
SimpleHash是一个强大的密码加密实用程序,可以帮助您保护Java应用程序的安全。SimpleHash结合使用salt和哈希算法,使攻击者更难破解密码。如果您正在构建一个需要密码加密的Java应用程序,那么SimpleHash绝对值得考虑。
Shiro的SimpleHash并非唯一选择,只是比较方便。