英文:
How to use PBKDF2 in java to get the same result as c#?
问题
Sure, here's the translated content:
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;
}
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);
}
Please note that the actual hashing algorithm in Java is "PBKDF2WithHmacSHA256"
, which uses SHA-256 for HMAC, as opposed to "HMACSHA1"
used in the C# example. Additionally, make sure to handle exceptions properly when using cryptographic functions in Java.
英文:
I want to convert my c# codes to java with PBKDF2 hashing and with the same result(no real product, just test).
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;
}
The result:
-
List item
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);
}
The result:
dxtD2eQ/4Sj5pGnPqCTiuL6jns5apO1OHkTaJC9DTzw=
答案1
得分: 1
为了让Java代码产生与C#代码相同的结果,只需在Java代码中将 PBKDF2WithHmacSHA256 替换为 PBKDF2WithHmacSHA1。
由于您没有发布示例的明文,我在测试中使用了明文
The quick brown fox jumps over the lazy dog
对于此明文,修复后的 Java代码和C#代码都返回
mPfEIpaydCQU15ACyPW+jPh/ctqi8q74aWhO9nWz9Q0=
英文:
So that the Java code gives the same result as the C# code, simply replace PBKDF2WithHmacSHA256 with PBKDF2WithHmacSHA1 in the Java code.
Since you didn't post the plaintext to your example, I use for my test the plaintext
The quick brown fox jumps over the lazy dog
for which the C# Code and the fixed Java Code both return
mPfEIpaydCQU15ACyPW+jPh/ctqi8q74aWhO9nWz9Q0=
as result.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论