java - 可以在 BCrypt 中设置明文或将其转换为盐吗?
问题描述
我对我们的密码加密练习有一个要求,其中密码的盐是静态的,并business_id+business_start_date
根据客户的业务 ID 和开始日期设置为 () 值。在 BCrypt 文档中,据说 BCrypt 在生成的哈希中内置了盐以防止彩虹表攻击。大多数示例使用 gensalt(int log_rounds) 函数。
IMO,我肯定会像其他人一样使用动态盐,因为它更容易实现。但是,如果仍然坚持实施静态盐哈希,有没有办法让 BCrypt 接受静态哈希或者;如果不可能,我可以使用哪些其他加密来满足该要求?
应用主要是80%的阅读内容,少量的创建、更新、删除操作。
我刚刚做了一个测试,我试图用静态盐对密码进行哈希处理。
此方法用于 BCrypt 实用程序类:
public static String hashPassWord(String textPassword, String salt){
String hashPassword = BCrypt.hashpw(textPassword, salt);
return hashPassword;
}
我正在测试的盐是纯文本,例如(busId:3,businessDate:2019-02-04)
String salt = new StringBuilder(busId).append(businessDate).toString();
我也有这种方法作为备用,轮数(工作量)设置为 10。
public static String hashPassword(String textPassword){
String salt = BCrypt.gensalt(workload);
String hashPassword = BCrypt.hashpw(textPassword, salt);
return hashPassword;
}
当 hashpw() 函数被执行时,Invalid Salt Version 错误被抛出到异常中。
解决方案
我已经根据 kelalaka 的评论实施了基础。这是 Bcrypt 库总是需要一个格式化的盐。根据您的明文大小,如果小于 BCRYPT_SALT_LEN,则 rnd 的其余部分填充随机字节,其余部分与库中的一样。
public static String gensalt(int log_rounds, SecureRandom random, String plaintextSalt) {
byte[] plaintextByte = plaintextSalt.getBytes();
byte rnd[] = new byte[BCRYPT_SALT_LEN];
//Use all of the string if size >= of the reqired rnd size
if (plaintextByte.length >= BCRYPT_SALT_LEN) {
System.arraycopy(plaintextByte, 0, rnd, 0, rnd.length);
} else {
//copy all of the string byte array
System.arraycopy(plaintextByte, 0, rnd, 0, plaintextByte.length);
//fill the rest with random
byte[] tempArray = new byte[BCRYPT_SALT_LEN - plaintextByte];
random.nextBytes(tempArray);
System.arraycopy(tempArray, 0, rnd, plaintextByte.length, temp.length);
}
StringBuffer rs = new StringBuffer();
rs.append("$2a$");
if (log_rounds < 10)
rs.append("0");
if (log_rounds > 30) {
throw new IllegalArgumentException(
"log_rounds exceeds maximum (30)");
}
rs.append(Integer.toString(log_rounds));
rs.append("$");
rs.append(encode_base64(rnd, rnd.length));
return rs.toString();
}
推荐阅读
- javascript - 如何使我的 javascript 中的正弦波正常工作?
- javascript - 如果字符串的总长度大于指定值(for循环),则缩短数组 - JavaScript
- python - 在 Android 上部署 Kivy 时没有错误但加载屏幕后应用程序崩溃
- java - 为什么 public static void main 方法不会在实例化的类中自动运行?
- android - Android:在外部存储中查找文件的最佳方式 2020
- sql - 简单 SQL Express 完全连接查询在应该返回空值时不返回
- python - Numpy 调整图像大小
- python - 如何使用 Beautiful Soup 查找嵌套列表中的所有链接
- flask - 如何在 Flask 中为每个请求创建一个 sqlalchemy 数据库会话?
- ssl - 临时 HTTP 403.16 禁止错误 - IIS