0

我正在尝试构建一个连接到 BitBns 加密交换 API(此处的文档)的 C# 应用程序。您可以导入他们必须轻松制作的邮递员工作区。

这是 pre-script 块中的 javascript 代码(您将在共享邮递员工作区中获得它),用于准备有效负载和签名:

使用密钥 = 0B1970CC1594BFB1820EC50DBC052761 密钥 = C6E10435B7C08CC6103CB5274DF4F23A

const timeStamp_nonce = Date.now().toString();
const body = JSON.parse(pm.request.body);
const secret = pm.environment.get("secret");
const obj = {
    timeStamp_nonce: timeStamp_nonce,
    body: JSON.stringify(body)
};
const payload = new Buffer(JSON.stringify(obj)).toString('base64');
const signature = CryptoJS.enc.Hex.stringify(CryptoJS.HmacSHA512(payload, secret));
pm.environment.set("body", JSON.stringify(body));
pm.environment.set("payload", payload);
pm.environment.set("signature", signature);

虽然此代码适用于邮递员发起的 API 调用,但下面的等效 C# 代码最终会出现 401 禁止响应。

string url = "https://api.bitbns.com/api/trade/v1/getApiUsageStatus/USAGE";
WebRequest request = WebRequest.Create(url);
        request.Method = "POST";
        request.ContentType = "application/x-www-form-urlencoded";
        request.Headers.Add("Accept-Charset", "utf-8");
        ((HttpWebRequest)request).Accept = "application/json";
        request.Headers.Add("X-BITBNS-APIKEY", "0B1970CC1594BFB1820EC50DBC052761");

        long timestamp = DateTimeOffset.Now.ToUnixTimeMilliseconds();

        Body body = new Body();
        Payload payload = new Payload();
        payload.timeStamp_nonce = timestamp.ToString();
        payload.body = JsonConvert.SerializeObject(value: body);
        string payloadHeader = JsonConvert.SerializeObject(payload);
        byte[] bytePayload = Encoding.UTF8.GetBytes(payloadHeader);
        string base64Payload = Convert.ToBase64String(bytePayload);
        request.Headers.Add("X-BITBNS-PAYLOAD", base64Payload);

        byte[] secretByte = Encoding.UTF8.GetBytes("C6E10435B7C08CC6103CB5274DF4F23A");
        //byte[] messageBytes = new ASCIIEncoding().GetBytes(payloadHeader);
        byte[] messageBytes = Encoding.UTF8.GetBytes(base64Payload);
        byte[] hashmessage = new HMACSHA512(secretByte).ComputeHash(messageBytes);
        
        //// to lowercase hexits
        string signature = String.Concat(Array.ConvertAll(hashmessage, x => x.ToString("x2")));
        request.Headers.Add("X-BITBNS-SIGNATURE", base64Payload);

        HttpWebResponse response = null;
        try
        {
            response = (HttpWebResponse)request.GetResponse();
        }
        catch (Exception exception)
        {
            Console.WriteLine(exception.Message);
            Console.Read();
        }

下面是 body 和 payload 类:

public class Body
{

}

public class Payload
{
    public string timeStamp_nonce = string.Empty;
    public string body;
}

密钥和秘密张贴在这里供您测试代码。这些来自一个空帐户,所以一切都很好。

我无法弄清楚 C# 中的哪个加密库将提供与 bitbns 给出的示例前脚本 javascript 代码相同的输出。

任何解决此问题的指针将不胜感激。

4

0 回答 0