在BCrypt中,已知前缀会导致哈希被破译,因为攻击者可以使用已知前缀来推断密码。这个问题可以通过增加密码强度来解决,例如使用更长的密码,或者添加额外的随机字节作为盐值。
另一个解决方法是使用随机的盐值,而不是固定的前缀。这可以通过在哈希函数中使用SecureRandom类来实现,该类会生成随机的盐值。以下是一个使用SecureRandom的示例代码:
import org.mindrot.jbcrypt.BCrypt;
import java.security.SecureRandom;
public class PasswordUtils {
private static final int workload = 12;
public static String hashPassword(String password) {
SecureRandom random = new SecureRandom();
byte[] salt = new byte[16];
random.nextBytes(salt);
String hashedPassword = BCrypt.hashpw(password, BCrypt.gensalt(workload, salt));
return(hashedPassword);
}
public static boolean checkPassword(String password, String hashedPassword) {
if (null == hashedPassword || !hashedPassword.startsWith("$2a$")) {
throw new IllegalArgumentException("Invalid hash provided for comparison");
}
return(BCrypt.checkpw(password, hashedPassword));
}
}
在示例代码中,我们使用SecureRandom类生成了一个随机的16字节盐值,并将其传递给genSalt()方法来生成哈希后的密码。这样,攻击者无法使用已知前缀来猜测密码。同时,如果攻击者尝试改变盐值或哈希值,hashPassword()方法会抛出异常。