Bitstamp - C#中的新身份验证 - 签名

Jul*_*ian 7 c# security hash web-services bitcoin

bitstamp的新身份验证说明如下:

Signature是HMAC-SHA256编码消息,包含:nonce,客户端ID和API密钥.必须使用通过API密钥生成的密钥生成HMAC-SHA256代码.此代码必须转换为十六进制表示形式(64个大写字符).示例(Python):message = nonce + client_id + api_key signature = hmac.new(API_SECRET,msg = message,digestmod = hashlib.sha256).hexdigest().上()

来源:链接

我有以下代码来添加新签名(和其他参数):

public void AddApiAuthentication(RestRequest restRequest)
    {
        var nonce = DateTime.Now.Ticks;
        var signature = GetSignature(nonce, apiKey, apiSecret, clientId);

        restRequest.AddParameter("key", apiKey);
        restRequest.AddParameter("signature", signature);
        restRequest.AddParameter("nonce", nonce);

    }

    private string GetSignature(long nonce, string key, string secret, string clientId)
    {
        string msg = string.Format("{0}{1}{2}", nonce,
            clientId,
            key);

        return ByteArrayToString(SignHMACSHA256(secret, StrinToByteArray(msg))).ToUpper();
    }
    public static byte[] SignHMACSHA256(String key, byte[] data)
    {
        HMACSHA256 hashMaker = new HMACSHA256(Encoding.ASCII.GetBytes(key));
        return hashMaker.ComputeHash(data);
    }

    public static byte[] StrinToByteArray(string str)
    {
        byte[] bytes = new byte[str.Length * sizeof(char)];
        System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
        return bytes;
    }

    public static string ByteArrayToString(byte[] hash)
    {
        return BitConverter.ToString(hash).Replace("-", "").ToLower();
    }
Run Code Online (Sandbox Code Playgroud)

然后我收到这个错误:

{"error":"无效签名"}

任何人都知道问题可能是什么?我检查了我的参数100次,那些没有错.也许有人为新的身份验证获得了一段代码(在C#中)?

UPDATE

Abhinav是对的,StringToByteArray方法错了(不仅是错字:P)工作代码是:

public static byte[] StrinToByteArray(string str)
    {
        return System.Text.Encoding.ASCII.GetBytes(str);
    }
Run Code Online (Sandbox Code Playgroud)

Abh*_*nav 5

您使用str.ToCharArray()StrinToByteArray是不正确的(仅在同一系统上使用时才正确).您需要使用ASCII编码或其他东西.

  • 你是我的英雄!小的更改(请参阅更新)使代码工作.也可以使用UTF8而不是我在测试后注意到的ASCII. (2认同)