Skip to content

Commit

Permalink
Add support for more BCrypt versions
Browse files Browse the repository at this point in the history
  • Loading branch information
wendigo committed Oct 4, 2024
1 parent c6ac83f commit c9da5cd
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 8 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
import java.security.spec.KeySpec;
import java.util.List;

import static at.favre.lib.crypto.bcrypt.BCrypt.Version.SUPPORTED_VERSIONS;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.io.BaseEncoding.base16;
import static java.nio.charset.StandardCharsets.UTF_8;
Expand All @@ -38,10 +39,10 @@ public final class EncryptionUtil

private EncryptionUtil() {}

public static int getBCryptCost(String password)
public static int getBCryptCost(BCrypt.Version version, String password)
{
try {
return BCrypt.Version.VERSION_2A.parser.parse(password.getBytes(UTF_8)).cost;
return version.parser.parse(password.getBytes(UTF_8)).cost;
}
catch (IllegalBCryptFormatException e) {
throw new HashedPasswordException("Invalid BCrypt password", e);
Expand Down Expand Up @@ -79,11 +80,13 @@ public static boolean doesPBKDF2PasswordMatch(String inputPassword, String hashe

public static HashingAlgorithm getHashingAlgorithm(String password)
{
if (password.startsWith("$2y")) {
if (getBCryptCost(password) < BCRYPT_MIN_COST) {
throw new HashedPasswordException("Minimum cost of BCrypt password must be " + BCRYPT_MIN_COST);
for (BCrypt.Version version : SUPPORTED_VERSIONS) {
if (password.startsWith(version.toString())) {
if (getBCryptCost(version, password) < BCRYPT_MIN_COST) {
throw new HashedPasswordException("Minimum cost of BCrypt password must be " + BCRYPT_MIN_COST);
}
return HashingAlgorithm.BCRYPT;
}
return HashingAlgorithm.BCRYPT;
}

if (password.contains(":")) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,10 @@ public class TestEncryptionUtil
@Test
public void testHashingAlgorithmBCrypt()
{
String password = "$2y$10$BqTb8hScP5DfcpmHo5PeyugxHz5Ky/qf3wrpD7SNm8sWuA3VlGqsa";
assertThat(getHashingAlgorithm(password)).isEqualTo(BCRYPT);
assertThat(getHashingAlgorithm("$2x$10$BqTb8hScP5DfcpmHo5PeyugxHz5Ky/qf3wrpD7SNm8sWuA3VlGqsa")).isEqualTo(BCRYPT);
assertThat(getHashingAlgorithm("$2y$10$BqTb8hScP5DfcpmHo5PeyugxHz5Ky/qf3wrpD7SNm8sWuA3VlGqsa")).isEqualTo(BCRYPT);
assertThat(getHashingAlgorithm("$2a$10$BqTb8hScP5DfcpmHo5PeyugxHz5Ky/qf3wrpD7SNm8sWuA3VlGqsa")).isEqualTo(BCRYPT);
assertThat(getHashingAlgorithm("$2b$10$BqTb8hScP5DfcpmHo5PeyugxHz5Ky/qf3wrpD7SNm8sWuA3VlGqsa")).isEqualTo(BCRYPT);
}

@Test
Expand Down

0 comments on commit c9da5cd

Please sign in to comment.