当前位置:网站首页>User password encryption using Bcrypt instead of MD5, SHA1 and SHA256
User password encryption using Bcrypt instead of MD5, SHA1 and SHA256
2022-07-30 07:09:00 【victorkevin】
Explain firstBcryptThe encoding algorithm has two advantages
- The ciphertext encoded by the same original text is different each time
- Encoding is slow
是的这就是Bcrypt的优点,This may seem odd to an experienced reader,That's pretty much it“优点”吗!Especially something like slow encoding.Here to illustrate this is called“优点”We have to start with the security of user password storage:
first mentionMD5Encoding Algorithm Everyone will immediately think that this is an encryption algorithm that can be cracked,The method of cracking is mainly used“彩虹表“(Not sure can search online),The above attack methods are basically the same as the original textMD5The same ciphertext is produced after encoding,(Simply put, the same password yields the same ciphertext,Then the original text can be deduced in reverse),Experienced developers will adoptsalt和多重MD5Encoding method to prevent the ciphertext from being cracked,If the attacker knows in advance or can obtain enough information, the above two methods are also easy to be broken,It is self-evident hereBcryptThe first advantage is to solve this problem.当然MD5is a relatively outdated hash encoding algorithm,For now it should be chosen even for simplicitySHA256and other relatively more secure hash coding algorithms.That second point why the encoding is so slow does it help,Before you think about attacking through rainbow tables, you must prepare a set of table collision tables with sufficient capacity in advance,如果能过MD5算法和Bcrypt作对比,因为BcryptSlow enough to cost more computation to generate the collision table,This difficulty can make generating collision tables impractical,Therefore, the difficulty of cracking increases accordingly,It is for the reasons mentioned aboveBcryptIt is more suitable to be used as an algorithm for encrypting and encoding user passwords,And no multiple encoding is involved in the process of use,Salt和Pepper等问题,So use itAPIMake the code more concise and understandable.
以下是BcryptImplementation of the encoding algorithm,The class is referenced fromSpring Security模块中的
org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder
/** * Implementation of PasswordEncoder that uses the BCrypt strong hashing function. Clients * can optionally supply a "strength" (a.k.a. log rounds in BCrypt) and a SecureRandom * instance. The larger the strength parameter the more work will have to be done * (exponentially) to hash the passwords. The default value is 10. * * @author Dave Syer * */
public class BCryptPasswordEncoder implements PasswordEncoder {
private Pattern BCRYPT_PATTERN = Pattern
.compile("\\A\\$2a?\\$\\d\\d\\$[./0-9A-Za-z]{53}");
private final Log logger = LogFactory.getLog(getClass());
private final int strength;
private final SecureRandom random;
public BCryptPasswordEncoder() {
this(-1);
}
/** * @param strength the log rounds to use, between 4 and 31 */
public BCryptPasswordEncoder(int strength) {
this(strength, null);
}
/** * @param strength the log rounds to use, between 4 and 31 * @param random the secure random instance to use * */
public BCryptPasswordEncoder(int strength, SecureRandom random) {
if (strength != -1 && (strength < BCrypt.MIN_LOG_ROUNDS || strength > BCrypt.MAX_LOG_ROUNDS)) {
throw new IllegalArgumentException("Bad strength");
}
this.strength = strength;
this.random = random;
}
public String encode(CharSequence rawPassword) {
String salt;
if (strength > 0) {
if (random != null) {
salt = BCrypt.gensalt(strength, random);
}
else {
salt = BCrypt.gensalt(strength);
}
}
else {
salt = BCrypt.gensalt();
}
return BCrypt.hashpw(rawPassword.toString(), salt);
}
public boolean matches(CharSequence rawPassword, String encodedPassword) {
if (encodedPassword == null || encodedPassword.length() == 0) {
logger.warn("Empty encoded password");
return false;
}
if (!BCRYPT_PATTERN.matcher(encodedPassword).matches()) {
logger.warn("Encoded password does not look like BCrypt");
return false;
}
return BCrypt.checkpw(rawPassword.toString(), encodedPassword);
}
}
测试的代码如下:
@Test
public void testBCryptPasswordEncoder() {
BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder(6);
for (int i = 0; i < 3; i++) {
String encodedText = bCryptPasswordEncoder.encode("567123TR");
System.out.println(String.format("第%dThe result of the secondary encoding:%s", i, encodedText));
}
}
最终测试的结果:
第0The result of the secondary encoding:$2a$06$ahAG0Hqch1kqCKueL8ecw.XFU8HHiO9k.HWuwXVd4iRiaVYd1Lko6
第1The result of the secondary encoding:$2a$06$IRmgGohEnNrC1xnhv0MomOly0AiIfBucBaTbx7QoZyj2lyilZCf9K
第2The result of the secondary encoding:$2a$06$dX.dZmRHMBC8RESaolKYU.u0cJmf70LRQbpnLvmZycOKPI4t34RJ2
扩展延伸
在某些应用场景BCryptis not applicable,If required by the systemDigest,HMac和AESScenarios for message authentication such as symmetric encryption,Such scenarios are when a common key needs to be shared,BcryptBecause the same original text outputs different keys,So there is no way to share the same key.
BcryptThe coding algorithm is applied to the blockchain technology,Many people have heard that the principle of Bitcoin mining is to findsha256Algorithms are calculated to satisfy certain conditionsnonce值,This calculation is to go through a lot of operations,Therefore, nodes with large computing power are more likely to receive mining rewards,This makes the block network controlled by a large amount of computing power,So some coins take this into account,用Bcrypt算法替代sha256It makes it impossible for miners to control the entire block network by investing computing power(因为Bcrypt算法慢),Interested readers can find relevant information.
Finally, based on the above suggestions, it is abandoned in the user password encryption encodingMD5吧,Because it is both outdated and insecure.
边栏推荐
- 使用kotlin扩展插件/依赖项简化代码(在最新版本4.0以后,此插件已被弃用,故请选择性学习,以了解为主。)
- Function functional interface and application
- 树莓派OpenCV+OpenCV-contrib
- nodejs PM2监控及报警邮件发送(二)
- 卷积神经网络(CNN)之卷积操作、池化操作、激活函数
- Meta分析在生态环境领域里的应用
- MySQL 索引优化及失效场景
- Servlet基本原理与常见API方法的应用
- Reasons and solutions for Invalid bound statement (not found)
- Configure MMdetection environment and train
猜你喜欢

Servlet基本原理与常见API方法的应用

R-GIS: 如何用R语言实现GIS地理空间分析及模型预测

边境的悍匪—机器学习实战:第十六章使用RNN和注意力机制进行自然语言处理

Function 函数式接口及应用

边境的悍匪—机器学习实战:第十五章 使用CNN和RNN处理序列

抽象工厂模式(Swift 实现)

MySQL data types and footprint

UAV ecological environment monitoring, image processing and GIS data analysis

二叉树(一):深度优先遍历与广度优先遍历

基于全球模式比较计划CMIP6与区域气候-化学耦合模式 WRF-Chem 的未来大气污染变化模拟
随机推荐
九、Kotlin基础学习:1、Companion的扩展方法和扩展属性;2、一般类的扩展方法和扩展属性;3、委托;
HSPF 模型应用
Rsync实现Win系统间的文件夹或数据同步
nodejs PM2监控及报警邮件发送(二)
Receive emails from gmail with pop3
Servlet basic principles and application of common API methods
边境的悍匪—机器学习实战:第十三章 使用TensorFlow加载和预处理数据
MySQL - Multi-table query and case detailed explanation
Xcode 绑定按钮点击事件
二十一、Kotlin进阶学习:实现简单的网络访问封装
R语言 生态环境领域应用
常用损失函数(一):Focal Loss
为什么会出现梯度爆炸和梯度消失现象?怎么缓解这种现象的发生?
Usage of exists in sql
MySQL - Function and Constraint Commands
目标检测中的知识蒸馏方法
用pop3收取gmail的邮件
大气颗粒物 PMF 源解析
[Ten years of network security engineers finishing] - 100 penetration testing tools introduction
边境的悍匪—机器学习实战:第一章 机器学习的基础知识