1

我在 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));     
} 

由于 Duncan 指出了 HMACSHA512 类,这是我提出的 C# 代码,但是我无法在不安装 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();
    }
4

1 回答 1

2

A SecretKeySpec is used to convert binary input into something that is recognised by Java security providers as a key. It does little more than decorate the bytes with a little post-it note saying "Pssst, it's an HmacSHA512 key...".

You can basically ignore it as a Java-ism. For your .NET code, you just need to find a way of declaring what the HMAC key is. Looking at the HMACSHA512 class, this seems quite straight-forward. There is a constructor that takes a byte array containing your key value.

于 2014-05-20T15:58:36.557 回答