c java hmacsha1,java-如何在C#中生成HMAC SHA1?

咸亦
2023-12-01

Vimvq1987答案的扩展:

return hashValue.ToString();无法产生您想要/需要的输出。 您必须将数组hashValue中的字节转换为其十六进制字符串表示形式。

可以像2983042691371631631618一样简单(打印大写字母A-F),或者如果您喜欢它则更复杂一些:

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

我得到完全相同的结果

$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 );

}

}

被拒绝了。 但是正如James在对此答案的评论中所指出的那样,至少使用using语句是一个好主意。

 类似资料: