简体   繁体   English

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

[英]What is the .NET Equivalent of Java's SecretKeySpec class?

I was provided the following code sample in Java and I'm having trouble converting it to C#. 提供了以下Java代码示例,但无法将其转换为C#。 How would I go about converting this so it'll work in .NET 4.5? 我将如何进行转换,使其在.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));     
} 

Here is the C# code that I've come up with thanks to Duncan pointing out the HMACSHA512 class, but I'm unable to verify the results match without installing java, which I can't do on this machine. 感谢Duncan指出了HMACSHA512类,这是我想出的C#代码,但是如果不安装java,我将无法验证结果是否匹配,而这在这台机器上是无法做到的。 Does this code match the above 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();
    }

A SecretKeySpec is used to convert binary input into something that is recognised by Java security providers as a key. SecretKeySpec用于将二进制输入转换为Java安全提供程序认为是密钥的内容。 It does little more than decorate the bytes with a little post-it note saying " Pssst, it's an HmacSHA512 key... ". 它所做的不只是用一点便条纸装饰字节说“ Pssst,这是HmacSHA512密钥... ”。

You can basically ignore it as a Java-ism. 您基本上可以将其视为Java主义而忽略。 For your .NET code, you just need to find a way of declaring what the HMAC key is. 对于您的.NET代码,您只需要找到一种声明HMAC密钥是什么的方法。 Looking at the HMACSHA512 class, this seems quite straight-forward. 查看HMACSHA512类,这似乎很简单。 There is a constructor that takes a byte array containing your key value. 有一个构造函数,它采用包含您的键值的字节数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM