【问题标题】:Equivalent code of hash in .Net to Python 2.7.Net 中与 Python 2.7 的等效哈希代码
【发布时间】: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


    【解决方案1】:

    终于可以解决这个问题了。我希望其他人也可以从中得到帮助

    import hmac
    import hashlib
    import base64
    import uuid
    import array
    
    erp_key = '7a640e1f-df45-4652-a9d5-4bdc2003deac'
    payload = 'ab38eadaeb746599f2c1ee90f8267f31f467347462764a24d71ac1843ee77fe3#40011234567890##34567####MitErpNavn#34567#20170719192159'
    
    erp_uuid = uuid.UUID(erp_key)
    map_arr = array.array('B', erp_uuid.bytes_le)
    makeitastring = "".join(chr(x) for x in map_arr)
    
    dig = hmac.new(makeitastring, payload, hashlib.sha256).digest()
    hash_key = base64.b64encode(dig).decode()
    
    encodedSignature = base64.encodestring(dig).replace('\n', '')
    
    print encodedSignature
    
    Output: f0UqIWmJBea+rTixF1jiCNhEt12yPN4R7gJclYMM3mE=
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-22
      • 1970-01-01
      • 1970-01-01
      • 2012-04-28
      • 1970-01-01
      • 1970-01-01
      • 2017-06-17
      • 2013-09-02
      相关资源
      最近更新 更多