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

SecretKeySpecは、バイナリ入力を Java セキュリティ プロバイダによってキーとして認識されるものに変換するために使用されます。それは、" Pssst、それは HmacSHA512 キーです... "という小さなポストイットでバイトを装飾するだけです。

基本的には、Java 主義として無視できます。.NET コードでは、HMAC キーが何であるかを宣言する方法を見つけるだけで済みます。HMACSHA512クラスを見ると、これは非常に簡単に見えます。キー値を含むバイト配列を取るコンストラクターがあります。

于 2014-05-20T15:58:36.557 に答える