从 Python 样本在 C# 中生成 HMAC-rsa256 签名

Generating HMAC-rsa256 Signature in C# from a Python sample

我一直在尝试使用三个参数生成 HMAC-rsa256 签名;一个以秒为单位的 Unix 时间戳,一个 API 密钥和一个 API 秘密,在 C#.Net 中用于以特定样式进行身份验证,但无法设法对示例代码中的步骤进行逆向工程 Python.

我试图破解步骤的Python代码是:

import hmac
import hashlib
import datetime
import json

def create_signature_Py27(key, secret):  # (string key, string secret) 
    timestamp = int(datetime.datetime.now().timestamp())  # UNIX timestamp in seconds
    string = "{}{}".format(timestamp, key)
    return hmac.new(secret, string, hashlib.sha256).hexdigest()

# Python 2.7 - 3.5+ 
# Note: latest versions of hmac lib requires 'secret' and 'string' as byte strings but not unicode
#
def create_signature(key, secret):  # (string key, string secret) 
    timestamp = int(datetime.datetime.now().timestamp())  # UNIX timestamp in seconds
    string = "{}{}".format(timestamp, key)
    return timestamp, hmac.new(secret.encode(), string.encode(), hashlib.sha256).hexdigest()

def auth_request(key, secret):
    timestamp, signature = create_signature(key, secret)
    return json.dumps({'e': 'auth',
        'auth': {'key': key, 'signature': signature, 'timestamp': timestamp,}, 'oid': 'auth', })

auth_request = auth_request('1WZbtMTbMbo2NsW12vOz9IuPM', '1IuUeW4IEWatK87zBTENHj1T17s'):

目前我尝试过的:

       public static string TEST(string timestamp4, string apikey1, string apisecret1)
       {


           HMACSHA256 hmc1 = new HMACSHA256(Encoding.ASCII.GetBytes(apisecret1));
           string mes = timestamp4 + apikey1;
           MessageBox.Show(mes);

           byte[] hmres1 = hmc1.ComputeHash(Encoding.ASCII.GetBytes(mes));
           string hex1 = BitConverter.ToString(hmres1).Replace("-", string.Empty);
           string b641 = Convert.ToBase64String(hmres1).Replace("=", "");
           MessageBox.Show(b641, "b64");
           return b641;                   // THIS TEST SIGNITURE RETURNS SOMETHING LIKE "asdaefcdvcxv/sdfdsfsd/fsd" , WHERE DOES THE "/" COMES FROM?
                                         //TIMESTAMP RETURNS WRONG VALUE WHICH THEN FEED INTO SIGNITURE FUNCTION- GIVING INVALID SIGNITURE( but its unix timestamp in sec's whish is expected)
}

但是有了这个,我无法重新生成正确的示例签名。示例 Apikey、Secret、timestamp 及其产品签名:

相反,我最终得到的签名是:

我尝试将参数一个一个地输入到加密函数中,但效果不佳。

当我使用 real 函数 生成带有真实 Api Key 和 Secret 以及实时时间戳的签名时,服务器返回的消息显示时间戳是不正确(但我看不出有任何问题),这也被输入到签名中,这可能完全是由于时间戳不正确,但即使使用提供的示例 ApiKey 和 Secret,测试函数生成完全不同的结构。(其中包含“/”和更短的)

到目前为止 Json 请求函数没有问题,但是,以防万一,它应该是这样的(给她的签名与上面的不同):

{ "e": "auth", "auth":{ "key":“1WZbtMTbMbo2NsW12vOz9IuPM。”, "signature": "02483c01efc26fac843dd34d0342d269bacf4daa906a32cb71806eb7467dcf58", "timestamp": 1448034533 } }

如果我错过了解释这个问题的任何现有主题,我提前道歉,如果有人能阐明这个问题,我将不胜感激。

您的方法return是签名的 base64 表示。

如果您改为 return hex1,您将获得大写的预期结果。如果你想要小写字母,return hex1.ToLower();