1

Help me please! I am trying to hash password using the pbkdf2-sha256 algorithm. Password = "user1", salt = "IFo7KXYswe7Fiu3BoVNOWg =", hashIterations = "27500". I know the result. It must be like "ZnxO94AYiTK7t+oj1PXpztVEQ+G82lFWt6VNStbhZpEuwzGMprjJVkAuEXgH1IQpZwmX1SrVtuMLN/JcM8GC4g==". Сhecked the result through the online encryptor(https://8gwifi.org/pbkdf.jsp) - matched.

online encryptor result

But, when I encrypt the password myself, I get a different result. Perhaps the problem is in the encoding. Where am I making a mistake? Thank you!

My code:

import org.apache.commons.codec.binary.Hex;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.spec.KeySpec;
import java.util.Base64;

String PASSWORD = "user1";
String SALT = "IFo7KXYswe7Fiu3BoVNOWg==";
int ITERATION_COUNT = 27500;
int KEY_LENGTH = 256;

KeySpec spec = new PBEKeySpec(
        PASSWORD.toCharArray(),
        SALT.getBytes(),
        ITERATION_COUNT,
        KEY_LENGTH
);
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
SecretKey secretKey = factory.generateSecret(spec);
byte[] hash = secretKey.getEncoded();

System.out.println("----hashStr----");
System.out.println(new String(hash, StandardCharsets.UTF_8));
System.out.println("----hashStrBase64----");
System.out.println(Base64.getEncoder().encodeToString(hash));
System.out.println("----hexHashString----");
System.out.println(Hex.encodeHexString(hash));

Result:

----hashStr----
=�I ��'��mh�W0y"��H��a�
�y 
----hashStrBase64----
Pe0BSRYglbEn+/htaPxXMA95IozqSJPisGGwChuheSA=
----hexHashString----
3ded0149162095b127fbf86d68fc57300f79228cea4893e2b061b00a1ba17920
0

1 Answer 1

3

The problem is SALT.getBytes().

This gets you the raw byte value of the salt.

However, it seems like the salt is encoded with Base64 (Base64 often appends =-signs so that the length matches and it only uses alphanumeric characters (plus some extra characters so you get 64 characters total), this can often be used to detect Base64).

From the online encrypter you use:

Input Base64 Empty salt will generate a random 16 bits salt value

You can use this to decode the Base64-salt:

KeySpec spec = new PBEKeySpec(
        PASSWORD.toCharArray(),
        Base64.getDecoder().decode(SALT),
        ITERATION_COUNT,
        KEY_LENGTH
);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.