









BCrypt 是一种专门用于密码存储的哈希算法,不是传统意义上可解密的加密方式。它由 Niels Provos 和 David Mazières 于 1999 年设计 ,核心特点是每次加密结果都不同(因为自动加盐),且计算速度可调节,能有效抵御暴力破解 。
BCrypt 的安全性由“工作因子”(也称为 strength 或 log rounds)决定。该值每增加 1,计算耗时约翻倍。
| 工作因子 (Cost) | 迭代次数 (2n) | 预估耗时 (现代 CPU) | 适用场景建议 |
|---|---|---|---|
| 10 | 1,024 | ~50-80 ms | 开发/测试环境,或对性能极度敏感且安全风险较低的内部系统。(默认值) |
| 12 | 4,096 | ~200-300 ms | 通用生产环境推荐起点。大多数互联网应用、电商平台的平衡选择。 |
| 14 | 16,384 | ~800ms - 1.2s | 高安全敏感系统(如金融、支付、医疗)。需确保服务器性能充足。 |
| >14 | >16,384 | >2s | 不推荐。除非有特殊合规要求,否则会导致用户登录明显卡顿,且容易引发并发下的 CPU 瓶颈。 |
为什么安全:
破解难度:
与其他算法对比:
<!-- BCrypt密码加密库 -->
<dependency>
<groupId>org.mindrot</groupId>
<artifactId>jbcrypt</artifactId>
<version>0.4</version>
</dependency>
package com.zibocoder.plugins.common.utils;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SmUtil;
import org.mindrot.jbcrypt.BCrypt;
/**
* @author zibocoder
* @date 2025/7/9 23:37:09
* @description 密码工具类
*/
public class PasswordUtil {
/**
* BCrypt密码加密(使用jBCrypt库)
* BCrypt.gensalt方法参数不写默认10,可用于开发测试环境,生产环境推荐值为 12
*/
public static String getBcryptEncryptPwd(String password) {
return BCrypt.hashpw(password, BCrypt.gensalt(12));
}
/**
* BCrypt密码验证(使用jBCrypt库)
* @param rawPassword 原始密码
* @param encodedPassword 已加密的密码
*/
public static boolean matches(String rawPassword, String encodedPassword) {
// 处理空值和空字符串情况
if (StrUtil.isBlank(rawPassword) || StrUtil.isBlank(encodedPassword)) {
return false;
}
return BCrypt.checkpw(rawPassword, encodedPassword);
}
public static void main(String[] args) {
System.out.println("\n=== BCrypt测试 ===");
String bcryptPwd1 = getBcryptEncryptPwd("123456");
String bcryptPwd2 = getBcryptEncryptPwd("123456");
System.out.println("BCrypt加密1: " + bcryptPwd1);
System.out.println("BCrypt加密2: " + bcryptPwd2);
System.out.println("两次加密结果不同(因为盐值不同): " + !bcryptPwd1.equals(bcryptPwd2));
System.out.println("BCrypt验证1: " + matches("123456", bcryptPwd1));
System.out.println("BCrypt验证2: " + matches("123456", bcryptPwd2));
System.out.println("错误密码验证: " + matches("wrong", bcryptPwd1));
}
}
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。