首页 > 解决方案 > 可以在 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 错误被抛出到异常中。

标签: javasecuritybcrypt

解决方案


我已经根据 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();

}

推荐阅读