[英]pbkdf2-sha256 hash algorithm issue
請幫幫我。 我正在嘗試使用 pbkdf2-sha256 算法對 hash 密碼,密碼 =“user1”,鹽 =“IFo7KXYswe7Fiu3BoVNOWg =”。 hashIterations = "27500"。 我知道結果。 它必須像“ZnxO94AYiTK7t+oj1PXpztVEQ+G82lFWt6VNStbhZpEuwzGMprjJVkAuEXgH1IQpZwmX1SrVtuMLN/JcM8GC4g==”。 通過在線加密器檢查結果( https://8gwifi.org/pbkdf.jsp ) - 匹配。
但是,當我自己加密密碼時,我得到了不同的結果。 也許問題在於編碼。 我在哪里犯錯? 謝謝!
我的代碼:
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
問題是SALT.getBytes()
。
這將為您提供鹽的原始字節值。
但是,似乎鹽是用 Base64 編碼的(Base64 通常會附加=
-signs 以便長度匹配,這通常可用於檢測 Base64)。
從您使用的在線加密器:
輸入 Base64 空鹽將生成一個隨機的 16 位鹽值
您可以使用它來解碼 Base64-salt:
KeySpec spec = new PBEKeySpec(
PASSWORD.toCharArray(),
Base64.getDecoder().decode(SALT),
ITERATION_COUNT,
KEY_LENGTH
);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.