如何在C#中生成HMAC-SHA1?

发布于 2024-11-08 13:52:28 字数 1396 浏览 0 评论 0原文

我正在尝试使用 C# 来使用 REST API。 API 创建者提供了 PHP、Ruby 和 Java 示例库。我对其中需要生成 HMAC< 的部分感到困惑/a>.

以下是他们提供的示例库中的实现方式。

PHP

hash_hmac('sha1', $signatureString, $secretKey, false);

Ruby

digest = OpenSSL::Digest::Digest.new('sha1')
return OpenSSL::HMAC.hexdigest(digest, secretKey, signatureString)

Java

SecretKeySpec signingKey = new SecretKeySpec(secretKey.getBytes(), HMAC_SHA1_ALGORITHM);

Mac mac = null;
mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
mac.init(signingKey);

byte[] bytes = mac.doFinal(signatureString.getBytes());

String form = "";
for (int i = 0; i < bytes.length; i++)
{
    String str = Integer.toHexString(((int)bytes[i]) & 0xff);
    if (str.length() == 1)
    {
        str = "0" + str;
    }

    form = form + str;
}
return form;

这是我在 C# 中的尝试。 它不起作用。更新:下面的 C# 示例运行得很好。我发现真正的问题是由于我的 signatureString 中的换行符存在一些跨平台差异。

var enc = Encoding.ASCII;
HMACSHA1 hmac = new HMACSHA1(enc.GetBytes(secretKey));
hmac.Initialize();

byte[] buffer = enc.GetBytes(signatureString);
return BitConverter.ToString(hmac.ComputeHash(buffer)).Replace("-", "").ToLower();

I am trying to make use of a REST API using C#. The API creator has provided sample libraries in PHP, Ruby and Java. I am getting hung up on one part of it where I need to generate an HMAC.

Here's how it is done in the sample libraries they have provided.

PHP

hash_hmac('sha1', $signatureString, $secretKey, false);

Ruby

digest = OpenSSL::Digest::Digest.new('sha1')
return OpenSSL::HMAC.hexdigest(digest, secretKey, signatureString)

Java

SecretKeySpec signingKey = new SecretKeySpec(secretKey.getBytes(), HMAC_SHA1_ALGORITHM);

Mac mac = null;
mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
mac.init(signingKey);

byte[] bytes = mac.doFinal(signatureString.getBytes());

String form = "";
for (int i = 0; i < bytes.length; i++)
{
    String str = Integer.toHexString(((int)bytes[i]) & 0xff);
    if (str.length() == 1)
    {
        str = "0" + str;
    }

    form = form + str;
}
return form;

Here's my attempt in C#. It is not working. UPDATE: The C# example below works just fine. I found out that the real problem was due to some cross-platform differences in newline characters in my signatureString.

var enc = Encoding.ASCII;
HMACSHA1 hmac = new HMACSHA1(enc.GetBytes(secretKey));
hmac.Initialize();

byte[] buffer = enc.GetBytes(signatureString);
return BitConverter.ToString(hmac.ComputeHash(buffer)).Replace("-", "").ToLower();

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

半寸时光 2024-11-15 13:52:28

Vimvq1987 的答案的扩展:

return hashValue.ToString(); 不会产生您想要/需要的输出。您必须将数组 hashValue 中的字节转换为其十六进制字符串表示形式。
可以像 return BitConverter.toString(hashValue); (打印大写字母 AF)一样简单,或者如果您喜欢更复杂一点:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.IO;

namespace ConsoleApplication1
{
    class Program
    {
        public static string Encode(string input, byte[] key)
        {
            HMACSHA1 myhmacsha1 = new HMACSHA1(key);
            byte[] byteArray = Encoding.ASCII.GetBytes(input);
            MemoryStream stream = new MemoryStream(byteArray);
            return myhmacsha1.ComputeHash(stream).Aggregate("", (s, e) => s + String.Format("{0:x2}",e), s => s );
        }


        static void Main(string[] args)
        {
            byte[] key = Encoding.ASCII.GetBytes("abcdefghijklmnopqrstuvwxyz");
            string input = "";
            foreach (string s in new string[] { "Marry", " had", " a", " little", " lamb" })
            {
                input += s;
                System.Console.WriteLine( Encode(input, key) );
            }
            return;
        }
    }
}

打印出来

3545e064fb59bc4bfc02b6e1c3d4925c898aa504
3249f4c8468d4d67f465937da05b809eaff22fdb
87baaadf5d096677f944015e53d283834eb1e943
6325376820c29a09e3ab30db000033aa71d6927d
54579b0146e2476595381d837ee38863be358213

并且我得到完全相同的

<?php
$secretKey = 'abcdefghijklmnopqrstuvwxyz';

$signatureString = '';
foreach( array('Marry',' had',' a',' little',' lamb') as $s ) {
    $signatureString .= $s;
    echo hash_hmac('sha1', $signatureString, $secretKey, false), "\n";
}

编辑结果: Dmitriy Nemykin 建议进行以下编辑

public static string Encode(string input, byte[] key)
{
    byte[] byteArray = Encoding.ASCII.GetBytes(input);
    using(var myhmacsha1 = new HMACSHA1(key))
    {
        var hashArray = myhmacsha1.ComputeHash(byteArray);
        return hashArray.Aggregate("", (s, e) => s + String.Format("{0:x2}",e), s => s );
    }
}

,但被拒绝。但正如詹姆斯在对此答案的评论中至少指出的那样 using 语句一个好点。

an extension to Vimvq1987's answer:

return hashValue.ToString(); doesn't produce the output you want/need. You have to convert the bytes in the array hashValue to their hex-string representation.
Can be as simple as return BitConverter.toString(hashValue); (prints upper-case letters A-F) or if you like it a bit more complex:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.IO;

namespace ConsoleApplication1
{
    class Program
    {
        public static string Encode(string input, byte[] key)
        {
            HMACSHA1 myhmacsha1 = new HMACSHA1(key);
            byte[] byteArray = Encoding.ASCII.GetBytes(input);
            MemoryStream stream = new MemoryStream(byteArray);
            return myhmacsha1.ComputeHash(stream).Aggregate("", (s, e) => s + String.Format("{0:x2}",e), s => s );
        }


        static void Main(string[] args)
        {
            byte[] key = Encoding.ASCII.GetBytes("abcdefghijklmnopqrstuvwxyz");
            string input = "";
            foreach (string s in new string[] { "Marry", " had", " a", " little", " lamb" })
            {
                input += s;
                System.Console.WriteLine( Encode(input, key) );
            }
            return;
        }
    }
}

which prints

3545e064fb59bc4bfc02b6e1c3d4925c898aa504
3249f4c8468d4d67f465937da05b809eaff22fdb
87baaadf5d096677f944015e53d283834eb1e943
6325376820c29a09e3ab30db000033aa71d6927d
54579b0146e2476595381d837ee38863be358213

and I get the exact same result for

<?php
$secretKey = 'abcdefghijklmnopqrstuvwxyz';

$signatureString = '';
foreach( array('Marry',' had',' a',' little',' lamb') as $s ) {
    $signatureString .= $s;
    echo hash_hmac('sha1', $signatureString, $secretKey, false), "\n";
}

edit: Dmitriy Nemykin suggested the following edit

public static string Encode(string input, byte[] key)
{
    byte[] byteArray = Encoding.ASCII.GetBytes(input);
    using(var myhmacsha1 = new HMACSHA1(key))
    {
        var hashArray = myhmacsha1.ComputeHash(byteArray);
        return hashArray.Aggregate("", (s, e) => s + String.Format("{0:x2}",e), s => s );
    }
}

which was rejected. But as James already pointed out in a comment to this answer at the very least the using statement is a good point.

七禾 2024-11-15 13:52:28

该网站有一些非常好的跨语言示例:http://jokecamp.wordpress .com/2012/10/21/examples-of-creating-base64-hashes-using-hmac-sha256-in- different-languages/

在撰写本文时,c# 实现是:

private string CreateToken(string message, string secret)
{
 secret = secret ?? "";
 var encoding = new System.Text.ASCIIEncoding();
 byte[] keyByte = encoding.GetBytes(secret);
 byte[] messageBytes = encoding.GetBytes(message);
 using (var hmacsha256 = new HMACSHA256(keyByte))
 {
 byte[] hashmessage = hmacsha256.ComputeHash(messageBytes);
 return Convert.ToBase64String(hashmessage);
 }
}

This site has some pretty good examples across languages: http://jokecamp.wordpress.com/2012/10/21/examples-of-creating-base64-hashes-using-hmac-sha256-in-different-languages/

The c# implementation at the time of writing is:

private string CreateToken(string message, string secret)
{
 secret = secret ?? "";
 var encoding = new System.Text.ASCIIEncoding();
 byte[] keyByte = encoding.GetBytes(secret);
 byte[] messageBytes = encoding.GetBytes(message);
 using (var hmacsha256 = new HMACSHA256(keyByte))
 {
 byte[] hashmessage = hmacsha256.ComputeHash(messageBytes);
 return Convert.ToBase64String(hashmessage);
 }
}
画尸师 2024-11-15 13:52:28

试试这个:

http://msdn.microsoft.com/ en-us/library/system.security.cryptography.hmacsha1.aspx

快速而肮脏的代码:

public string Encode(string input, byte [] key)
{
        HMACSHA1 myhmacsha1 = new HMACSHA1(key);
        byte[] byteArray = Encoding.ASCII.GetBytes( input );
        MemoryStream stream = new MemoryStream( byteArray ); 
        byte[] hashValue = myhmacsha1.ComputeHash(stream);
        return hashValue.ToString();
}

Try this:

http://msdn.microsoft.com/en-us/library/system.security.cryptography.hmacsha1.aspx

quick and dirty code:

public string Encode(string input, byte [] key)
{
        HMACSHA1 myhmacsha1 = new HMACSHA1(key);
        byte[] byteArray = Encoding.ASCII.GetBytes( input );
        MemoryStream stream = new MemoryStream( byteArray ); 
        byte[] hashValue = myhmacsha1.ComputeHash(stream);
        return hashValue.ToString();
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文