pbkdf2-sha256 哈希算法问题

时间:2021-04-14 14:41:05

标签: java

请帮帮我! 我正在尝试使用 pbkdf2-sha256 算法散列密码。 密码 = "user1", salt = "IFo7KXYswe7Fiu3BoVNOWg = ", hashIterations = "27500"。 我知道结果。它必须像“ZnxO94AYiTK7t+oj1PXpztVEQ+G82lFWt6VNStbhZpEuwzGMprjJVkAuEXgH1IQpZwmX1SrVtuMLN/JcM8GC4g==”。 通过在线加密器检查结果(https://8gwifi.org/pbkdf.jsp) - 匹配。

online encryptor result

但是,当我自己加密密码时,我得到了不同的结果。也许问题出在编码上。我在哪里犯了错误?谢谢!

我的代码:

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));

结果:

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

1 个答案:

答案 0 :(得分:2)

问题是SALT.getBytes()

这会为您提供盐的原始字节值。

但是,salt 似乎是用 Base64 编码的(Base64 经常附加 = 符号以便长度匹配,这通常可用于检测 Base64)。

来自您使用的在线加密器:

<块引用>

输入 Base64 Empty salt 会生成一个随机的 16 位 salt 值

您可以使用它来解码 Base64-salt:

KeySpec spec = new PBEKeySpec(
        PASSWORD.toCharArray(),
        Base64.getDecoder().decode(SALT),
        ITERATION_COUNT,
        KEY_LENGTH
);
相关问题