什么是Java的SecretKeySpec类的.NET等价物?
问题描述:
我在Java中被提供了下面的代码示例,我很难将它转换为C#。我怎么去转换这个,所以它可以在.NET 4.5中工作?什么是Java的SecretKeySpec类的.NET等价物?
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#代码,我已经拿出感谢邓肯指出的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安全供应商公认的关键的东西。它只是用一个小小的便笺注释说“Pssst,它是一个HmacSHA512密钥...”来装饰字节。
你基本上可以忽略它作为Java-ISM。对于你的.NET代码,你只需要找到一种方法来声明HMAC密钥是什么。看看HMACSHA512
课程,这看起来很直截了当。有一个构造函数需要一个包含您的键值的字节数组。
澄清你遇到的具体问题。 .NET有一个[SHA512类。](http://msdn.microsoft.com/en-us/library/system.security.cryptography.sha512.aspx) –
在C#中,没有称为SecretKeySpec或Mac的类。我想我不理解C#等同于那些。这不是我的专业领域。 –
SecretKeySpec [此处记录](http://docs.oracle.com/javase/7/docs/api/javax/crypto/spec/SecretKeySpec.html)。它似乎使用您指定的指定算法生成“密钥”。我真的不知道它是如何工作的,但你可以尝试从它获得一些值,并将它们与.NET SHA512类的输出进行比较,看看它们是否同意。 –