如何在 java 中使用 PBKDF2 以获得与 c# 相同的结果?
How to use PBKDF2 in java to get the same result as c#?
我想使用 PBKDF2 哈希将我的 c# 代码转换为 java,并得到相同的结果(没有真正的产品,只是测试)。
C#:
static string Pbkdf2Hashing(string password)
{
byte[] salt = new byte[128 / 8];
string hashed = Convert.ToBase64String(KeyDerivation.Pbkdf2(
password: password,
salt: salt,
prf: KeyDerivationPrf.HMACSHA1,
iterationCount: 10000,
numBytesRequested: 256 / 8));
return hashed;
}
结果:
列表项
oudaCubzWVIMjTxaQh1KT85fn+p2KjQRdBDXpiS8AUA=
Java:
static String Pbkdf2Hashing(String password) throws Exception {
byte[] salt = new byte[128 / 8];
int iterations = 10000;
int derivedKeyLength = 256;
KeySpec spec = new PBEKeySpec(password.toCharArray(), salt, iterations, derivedKeyLength);
SecretKeyFactory f = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
byte[] result = f.generateSecret(spec).getEncoded();
return Base64.getEncoder().encodeToString(result);
}
结果:
dxtD2eQ/4Sj5pGnPqCTiuL6jns5apO1OHkTaJC9DTzw=
为了使 Java 代码给出与 C# 代码相同的结果,只需将 PBKDF2WithHmacSHA256 替换为 PBKDF2WithHmacSHA1 Java代码。
因为你没有post你的例子的明文,我用明文来测试
The quick brown fox jumps over the lazy dog
C# 代码和 fixed Java 代码都 return
mPfEIpaydCQU15ACyPW+jPh/ctqi8q74aWhO9nWz9Q0=
作为结果。
我想使用 PBKDF2 哈希将我的 c# 代码转换为 java,并得到相同的结果(没有真正的产品,只是测试)。
C#:
static string Pbkdf2Hashing(string password)
{
byte[] salt = new byte[128 / 8];
string hashed = Convert.ToBase64String(KeyDerivation.Pbkdf2(
password: password,
salt: salt,
prf: KeyDerivationPrf.HMACSHA1,
iterationCount: 10000,
numBytesRequested: 256 / 8));
return hashed;
}
结果:
列表项
oudaCubzWVIMjTxaQh1KT85fn+p2KjQRdBDXpiS8AUA=
Java:
static String Pbkdf2Hashing(String password) throws Exception {
byte[] salt = new byte[128 / 8];
int iterations = 10000;
int derivedKeyLength = 256;
KeySpec spec = new PBEKeySpec(password.toCharArray(), salt, iterations, derivedKeyLength);
SecretKeyFactory f = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
byte[] result = f.generateSecret(spec).getEncoded();
return Base64.getEncoder().encodeToString(result);
}
结果:
dxtD2eQ/4Sj5pGnPqCTiuL6jns5apO1OHkTaJC9DTzw=
为了使 Java 代码给出与 C# 代码相同的结果,只需将 PBKDF2WithHmacSHA256 替换为 PBKDF2WithHmacSHA1 Java代码。
因为你没有post你的例子的明文,我用明文来测试
The quick brown fox jumps over the lazy dog
C# 代码和 fixed Java 代码都 return
mPfEIpaydCQU15ACyPW+jPh/ctqi8q74aWhO9nWz9Q0=
作为结果。