0

I'm trying to write a password hashing function using PBKDF2 and Bouncy Castle as the provider. I'm new to cryptography, so the majority of the code below was taken from another SO post. However, every time I run the function for a given password, it produces the same hash. Shouldn't the hash be different, considering I'm generating a new salt each time from the Secure Random object? Here is the code:

    SecureRandom random = new SecureRandom();
    byte[] salt = new byte[8];
    final int iterationCount = 20000;
    final int keyLength = 256;
    random.nextBytes(salt);

    try {
         SecretKeyFactory factoryBC =  SecretKeyFactory.getInstance("PBKDF2WithHmacSHA3-256", "BC");
         KeySpec keySpecBC = new PBEKeySpec(password.toCharArray(), salt, iterationCount, keyLength);
         SecretKey keyBC = factoryBC.generateSecret(keySpecBC);
         String hashedPW = keyBC.getEncoded().toString();
         }

For example, if I pass in the string "hello", I will get back "[B@44af588b" each time.

  • 1
    Try and show the output of the bytes using a base 64 or hexadecimal encoder. What you are currently looking at is the *reference to the object* printed out as string, as byte arrays don't implement a special `toString()` method themselves. Java 17+ has HexFormat, or otherwise there is an [so Q/A](https://stackoverflow.com/q/9655181/589259) – Maarten Bodewes Nov 07 '22 at 23:30
  • In Java you can not print `byte[]` types using `toString()` (or if you do you only get a string like you did). Please learn how to properly print the content of byte arrays e.g. encode it hex or base64. – Robert Nov 08 '22 at 08:23

0 Answers0