gpt4 book ai didi

c# - Java 的 SecretKeySpec 类的 .NET 等效项是什么?

转载 作者:行者123 更新时间:2023-11-30 03:53:47 26 4
gpt4 key购买 nike

我获得了以下 Java 代码示例,但我在将其转换为 C# 时遇到了问题。我将如何对其进行转换,以便它可以在 .NET 4.5 中工作?

public static String constructOTP(final Long counter, final String key) 
throws NoSuchAlgorithmException, DecoderException, InvalidKeyException
{
// setup the HMAC algorithm, setting the key to use
final Mac mac = Mac.getInstance("HmacSHA512");

// convert the key from a hex string to a byte array
final byte[] binaryKey = Hex.decodeHex(key.toCharArray());

// initialize the HMAC with a key spec created from the key
mac.init(new SecretKeySpec(binaryKey, "HmacSHA512"));

// compute the OTP using the bytes of the counter
byte[] computedOtp = mac.doFinal(
ByteBuffer.allocate(8).putLong(counter).array());

//
// increment the counter and store the new value
//

// return the value as a hex encoded string
return new String(Hex.encodeHex(computedOtp));
}

这是我想出的 C# 代码,感谢 Duncan 指出了 HMACSHA512 类,但我无法在不安装 java 的情况下验证结果匹配,而我在这台机器上无法做到这一点。这段代码与上面的 Java 匹配吗?

    public string ConstructOTP(long counter, string key)
{
var mac = new HMACSHA512(ConvertHexStringToByteArray(key));
var buffer = BitConverter.GetBytes(counter);

Array.Resize(ref buffer, 8);

var computedOtp = mac.ComputeHash(buffer);

var hex = new StringBuilder(computedOtp.Length * 2);

foreach (var b in computedOtp)
hex.AppendFormat("{0:x2", b);

return hex.ToString();
}

最佳答案

SecretKeySpec 用于将二进制输入转换为 Java 安全提供程序可识别为 key 的内容。它只不过是用一个小便利贴来装饰字节,上面写着“嘘,这是一个 HmacSHA512 key ...”。

你基本上可以忽略它作为 Java 主义。对于您的 .NET 代码,您只需要找到一种声明 HMAC key 的方法即可。看着HMACSHA512类,这看起来很简单。有一个构造函数接受包含您的键值的字节数组。

关于c# - Java 的 SecretKeySpec 类的 .NET 等效项是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23764452/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com