我有一个用Java编写并使用HmacSha1进行密码哈希处理的应用程序。我们正在尝试将应用程序迁移到dotnet core。
我已经为下面的Java代码编写了如下的点网代码,以创建Key和哈希值。
Java代码:
public static String encryptPassword(String pLogin, String pPassword)
{
try
{
byte[] salt = pLogin.getBytes();
SecretKeySpec secret = getSecret(pPassword, salt, 10000, 512, "HmacSHA1");
//String keystring = BinaryToTextEncoders.encode("base64", secret.getEncoded());
//System.out.println("key:" + keystring);
byte[] data = getHashOfPassword(secret, pPassword, "HmacSHA1");
Base16Encoder encode = new Base16Encoder();
return encode.encode(data);
}
catch (NoSuchAlgorithmException exc) {
exc.printStackTrace();
return pPassword;
}
catch (InvalidKeySpecException exc) {
return pPassword;
}
catch (UnsupportedEncodingException exc) {
return pPassword;
}
catch (InvalidKeyException exc) {}
return pPassword;
}
private static SecretKeySpec getSecret(String password, byte[] salt, int iterations, int keyLength, String algorithm)
throws UnsupportedEncodingException, InvalidKeySpecException, NoSuchAlgorithmException {
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2With" + algorithm);
KeySpec spec = new PBEKeySpec(password.toCharArray(), salt, iterations, keyLength);
SecretKey tmp = factory.generateSecret(spec);
System.out.println("Raw output of keys"+tmp.getEncoded());
return new SecretKeySpec(tmp.getEncoded(), algorithm);
}
private static byte[] getHashOfPassword(SecretKeySpec secret, String plainPassword, String algorithm)
throws NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException {
Mac mac = Mac.getInstance(algorithm);
mac.init(secret);
byte[] password = plainPassword.getBytes("UTF-8");
byte[] hashedPassword = mac.doFinal(password);
return hashedPassword;
}
我编写的替换上面的点网代码:
byte[] salt = Encoding.UTF8.GetBytes(secret);
System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();
byte[] messageBytes = Encoding.UTF8.GetBytes(password);
String hashedvalue = "";
var pbkdf2 = new Rfc2898DeriveBytes(messageBytes, salt, 10000);
var key = pbkdf2.GetBytes(512);
Console.WriteLine("key---------:", key);
var hmacsha1 = new HMACSHA1(key);
byte[] hashmessage = hmacsha1.ComputeHash(messageBytes);
hashedvalue = Encode(hashmessage);
从Java代码和dotnet代码生成的密钥不同的问题。
我想提出建议,在dotnet中SecretKeyFactory的等效类是什么,或者我怎样才能生成与Java中相同的密钥