'pbkdf2-sha256 hash algorithm issue
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.
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
Solution 1:[1]
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
);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |