当前位置:网站首页>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.
边栏推荐
猜你喜欢
Generalized Focal Loss 论文阅读笔记
基于全球模式比较计划CMIP6与区域气候-化学耦合模式 WRF-Chem 的未来大气污染变化模拟
七、Kotlin基础学习:1、创建类;2、构造函数;3、继承;4、封装;5、抽象类;6、接口;7、嵌套类;8、内部类;9、枚举类
十九、Kotlin进阶学习:1、管道数据的收和发;2、管道的关闭;3、生产者和消费者;4、管道的缓存区;
抽象工厂模式(Swift 实现)
Based on R language geographic weighted regression, principal component analysis, discriminant analysis and other spatial heterogeneity data analysis
八、Kotlin基础学习:1、数据类;2、单例;3、伴生对象;4、密封类;
单例模式:Swift 实现
九、Kotlin基础学习:1、Companion的扩展方法和扩展属性;2、一般类的扩展方法和扩展属性;3、委托;
Mycat2.0 build tutorial
随机推荐
Jdbc & Mysql timeout analysis
Go简单实现协程池
Servlet基本原理与常见API方法的应用
Kaggle-M5
Redis 发布/订阅
Twenty-two, Kotlin advanced learning: simply learn RecyclerView to achieve list display;
Detailed introduction to the usage of Nacos configuration center
目标检测中的知识蒸馏方法
Arthas 命令解析(watch/tt/sc)
学生成绩管理系统(C语言版)
标准化(Normalization)知识点总结
Flink-stream/batch/OLAP integrated to get Flink engine
HSPF 模型应用
Nacos配置中心用法详细介绍
边境的悍匪—机器学习实战:第十章 Keras人工神经网络简介
TDengine cluster construction
基于PyTorch深度学习无人机遥感影像目标检测、地物分类及语义分割
Thread state of five
Bubble sort, selection sort, insertion sort, quick sort
Xcode 建立 UIKit 项目(Hello World)