How to write the follow simple sha1Hex() in C#(.net) ?
How to write the follow simple sha1Hex(sbyte[] data, string key) in C#(.net) ?
下面是Java的代码,c#要怎么写这个简单的算法,要带key的。
public static string sha1Hex(sbyte[] data, string key)
{
sbyte[] keyBytes = key.GetBytes();
SecretKeySpec signingKey = new SecretKeySpec(keyBytes, "HmacSHA1");
Mac mac;
StringBuilder sb = new StringBuilder();
try
{
mac = Mac.getInstance("HmacSHA1");
mac.init(signingKey);
sbyte[] rawHmac = mac.doFinal(data);
foreach (sbyte b in rawHmac)
{
sb.Append(byteToHexString(b));
}
}
catch (Exception)
{
}
return sb.ToString();
}
真希的五月
9 years, 2 months ago
Answers
解说
可以用
HMAC.Create(hmacname)
来创建
HMAC
实例。这里 hmacname 包括如下一些(但不完全)
-
hmacmd5
-
hmacsha1
-
hmacsha256
-
hmacsha384
-
hmacsha512
之后设置
HMAC
实例的
Key
:
hamc.Key = ....
之后再计算得到结果就好
hmac.ComputeHash(data)
,这里
data
可以是个
byte[]
也可以是
Stream
。
把字符串变成
byte[]
可以用
Encoding.GetBytes()
实例方法,常用的 Encoding 有
-
Encoding.Default
,系统默认的编码,比如中文 Windows 是 GBK -
Encoding.UTF8
最后需要把结果
byte[]
变成十六进制,
BitConvert.ToString(byte[])
可以做到,不过得到的是像这样的:
12-34-56-78-AB-CD
,如果不需要间隔符可以把
-
号替换掉。
示例
https://dotnetfiddle.net/su16Ve
public static string Sha1Hex(byte[] data, string key) {
HMAC hmac = HMAC.Create("hmacsha1");
hmac.Key = Encoding.UTF8.GetBytes(key);
var code = hmac.ComputeHash(data);
return BitConverter.ToString(code).Replace("-", string.Empty);
}
qopx123
answered 9 years, 2 months ago
http://stackoverflow.com/a/6533030/2586541
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;
}
}
}
星期一的马甲
answered 9 years, 2 months ago