PBEKeySpec 使用字节数组参数而不是 ASCII
2022-09-03 15:00:40
我想知道是否有一种方法可以与字节数组参数一起使用。PBEKeySpec
请找到以下文档的链接:
http://docs.oracle.com/javase/1.7/docs/api/javax/crypto/spec/PBEKeySpec.html)
我想知道是否有一种方法可以与字节数组参数一起使用。PBEKeySpec
请找到以下文档的链接:
http://docs.oracle.com/javase/1.7/docs/api/javax/crypto/spec/PBEKeySpec.html)
以下是我的解决方案:我把它放在谷歌上。请考虑我必须在内部复制密码和盐,因为它们来自外部时具有另一种格式,但结果是相同的。它似乎有效并解决了将密码作为byte[]而不是char[]的问题(它让我发疯),我希望它有帮助!干杯,苏斯塔
public class Pbkdf2 {
public Pbkdf2() {
}
public void GenerateKey(final byte[] masterPassword, int masterPasswordLen,
final byte[] salt, int saltLen,
int iterationCount, int requestedKeyLen,
byte[] generatedKey) {
byte[] masterPasswordInternal = new byte[masterPasswordLen];
System.arraycopy(masterPassword, 0, masterPasswordInternal, 0, masterPasswordLen);
byte[] saltInternal = new byte[saltLen];
System.arraycopy(salt, 0, saltInternal, 0, saltLen);
SecretKeySpec keyspec = new SecretKeySpec(masterPasswordInternal, "HmacSHA1");
Mac prf = null;
try {
prf = Mac.getInstance("HmacSHA1");
prf.init(keyspec);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
}
int hLen = prf.getMacLength(); // 20 for SHA1
int l = Math.max(requestedKeyLen, hLen); // 1 for 128bit (16-byte) keys
int r = requestedKeyLen - (l - 1) * hLen; // 16 for 128bit (16-byte) keys
byte T[] = new byte[l * hLen];
int ti_offset = 0;
for (int i = 1; i <= l; i++) {
F(T, ti_offset, prf, saltInternal, iterationCount, i);
ti_offset += hLen;
}
System.arraycopy(T, 0, generatedKey, 0, requestedKeyLen);
}
private static void F(byte[] dest, int offset, Mac prf, byte[] S, int c, int blockIndex) {
final int hLen = prf.getMacLength();
byte U_r[] = new byte[hLen];
// U0 = S || INT (i);
byte U_i[] = new byte[S.length + 4];
System.arraycopy(S, 0, U_i, 0, S.length);
INT(U_i, S.length, blockIndex);
for (int i = 0; i < c; i++) {
U_i = prf.doFinal(U_i);
xor(U_r, U_i);
}
System.arraycopy(U_r, 0, dest, offset, hLen);
}
private static void xor(byte[] dest, byte[] src) {
for (int i = 0; i < dest.length; i++) {
dest[i] ^= src[i];
}
}
private static void INT(byte[] dest, int offset, int i) {
dest[offset + 0] = (byte) (i / (256 * 256 * 256));
dest[offset + 1] = (byte) (i / (256 * 256));
dest[offset + 2] = (byte) (i / (256));
dest[offset + 3] = (byte) (i);
}
}
我必须实现一个两阶段的 pbkdf2 派生(所以第二个 pbkdf2 的字节来自第一个作为输入)。我最终使用了BouncyCastle,因为我无法让字节数组来字符数组体操。从另一个问题中感谢Pasi:用于JAVA的PBKDF2-HMAC-SHA256的可靠实现
import org.bouncycastle.crypto.generators.PKCS5S2ParametersGenerator;
import org.bouncycastle.crypto.digests.SHA256Digest;
import org.bouncycastle.crypto.digests.GeneralDigest;
import org.bouncycastle.crypto.params.KeyParameter;
GeneraDigest algorithm = new SHA256Digest();
PKCS5S2ParametersGenerator gen = new PKCS5S2ParametersGenerator(algorithm);
gen.init(passwordBytes, salt, iterations);
byte[] dk = ((KeyParameter) gen.generateDerivedParameters(256)).getKey();