【发布时间】:2017-12-25 08:24:12
【问题描述】:
我在 .Net 中有一个代码来生成 HMAC SHA256 哈希。我尽力在 Python 2.7 中获取等效代码,但它有所不同。我哪里错了?
.net 代码
using System;
using System.Security.Cryptography;
using System.Text;
public class Program
{
public static void Main()
{
var key = Guid.Parse("7a640e1f-df45-4652-a9d5-4bdc2003deac").ToByteArray();
var payload = Encoding.UTF8.GetBytes("ab38eadaeb746599f2c1ee90f8267f31f467347462764a24d71ac1843ee77fe3#40011234567890##34567####MitErpNavn#34567#20170719192159");
Console.WriteLine(key);
Console.WriteLine(payload);
for(var i = 0; i < key.Length;i++)
{
var b = key[i];
Console.WriteLine(b);
}
using(var ha = new HMACSHA256(key))
{
var hash = ha.ComputeHash(payload);
var result = Convert.ToBase64String(hash);
Console.WriteLine(result);
}
}
}
Output: f0UqIWmJBea+rTixF1jiCNhEt12yPN4R7gJclYMM3mE=
Python 2.7
import hmac
import hashlib
import base64
import uuid
erp_key = '7a640e1f-df45-4652-a9d5-4bdc2003deac'
payload = 'ab38eadaeb746599f2c1ee90f8267f31f467347462764a24d71ac1843ee77fe3#40011234567890##34567####MitErpNavn#34567#20170719192159'
erp_uuid = uuid.UUID(erp_key)
dig = hmac.new(erp_uuid.bytes, msg=payload, digestmod=hashlib.sha256).digest()
hash_key = base64.b64encode(dig).decode()
print hash_key
Output: wI/WinRP4mHfHLnFCSHn6j4VphSOO8CjLqkAVJi1HTQ=
【问题讨论】:
标签: .net python-2.7 sha256 hmac