org.apache.commons.codec.digest.Crypt leads to Invalid salt value exception

Viewed 276

The following code leads to java.lang.IllegalArgumentException randomly but not always and on one computer, not other used for testing. Reason for the exception is Invalid salt value: $6$+E3Vebci/+lhkquntg==. When calling Crypt.crypt() using SHA512 ($6$). I can see that the Crypt has a pattern to check against for valid salt: ā€œ^\\$([56])\\$(rounds=(\\d+)\\$)?([\\.\\/a-zA-Z0-9]{1,16}).*ā€œ.

JDK is openjdk 15.0.1 2020-10-20, and commons-codec is version 1.15.

I am just wondering why this happens randomly and on one Windows 10 computer but not on another (macOS Big Sur on M1). And should I then create the salt somehow differently to avoid having this exception? Didn't find anything similar when searching from the internet.

byte bytes[] = new byte[13]; 
secureRandom.nextBytes(bytes); // java.security.SecureRandom
String saltBytes = new String(Base64.getEncoder().encode(bytes));
String salt = "$6$" + saltBytes;
String hashedPassword = Crypt.crypt(user.getPassword(), salt);

Stack trace ends at org.apache.commons.codec.digest.Sha2Crypt.sha2Crypt at line 181.

PC is MateBook D Intel Core i7-855OU, Windows 10 Home v 1909 build 18363.1379

1 Answers

From the documentation of crypto(String key, String salt)

The exact algorithm depends on the format of the salt string:

  • SHA-512 salts start with $6$ and are up to 16 chars long.
    ...
    The rest of the salt string is drawn from the set [a-zA-Z0-9./] and is cut at the maximum length of if a "$" sign is encountered.
    ...
    Throws:
    IllegalArgumentException - if the salt does not match the allowed pattern

As Base64 encoded string may contains "=", "+", which are not allowed in the regex [a-zA-Z0-9./], you will see error randomly when some invalid character appear in the generated salt.

Solutions:

  1. Simply use crypto(String key) instead as it already provides random salt.
  2. Or generate salt following the allowed pattern.

Reference:
rfc4648 - Table 1: The Base 64 Alphabet

Related