R语言调用NiceHash API时HMAC签名返回2000错误问题求助
解决方案
1. 构造带空分隔符的输入原始向量
R的普通字符串不支持嵌入NUL(\x00)字符,所以不要用paste0拼接输入内容,改用原始字节向量拼接各个字段和空分隔符即可规避报错:
library(openssl) library(httr) library(uuid) # 定义各个输入字段 APIKey <- "你的API Key" APISecret <- "你的Secret Key" XTime <- as.character(round(as.numeric(Sys.time())*1000)) # 生成毫秒级时间戳 XNonce <- UUIDgenerate() # 生成随机nonce OrgID <- "你的组织ID" method <- "GET" endpoint <- "/main/api/v2/accounting/accounts2" query <- "" # 无查询参数留空,有参数按key=value&key2=value2格式拼接即可 # 定义空字节常量 nul <- as.raw(0) # 按官方要求顺序拼接原始字节:APIKey + NUL + XTime + NUL + XNonce + NUL + NUL + OrgID + NUL + NUL + 请求方法 + NUL + 接口路径 + NUL + 查询参数 input_raw <- c( charToRaw(APIKey), nul, charToRaw(XTime), nul, charToRaw(XNonce), nul, nul, charToRaw(OrgID), nul, nul, charToRaw(method), nul, charToRaw(endpoint), nul, charToRaw(query) )
2. 生成符合要求的HMAC-SHA256签名
使用openssl包的hmac方法处理原始字节输入,确保输出为小写十六进制格式:
# 生成签名 signature <- hmac( key = APISecret, object = input_raw, algo = "sha256", as_raw = FALSE ) # 拼接X-Auth请求头内容 XAuth <- paste0(APIKey, ":", signature)
3. 修正请求结构
GET请求不需要携带Content-Type请求头,多余的头会导致签名校验失败:
# 发起请求 response <- GET( url = paste0("https://api2.nicehash.com", endpoint), add_headers( `X-Time` = XTime, `X-Nonce` = XNonce, `X-Organization-Id` = OrgID, `X-Auth` = XAuth ) ) # 打印返回结果验证 print(content(response, "text"))
测试验证
你提供的测试用例使用上述方法处理后,生成的签名和预期结果21e6a16f6eb34ac476d59f969f548b47fffe3fea318d9c99e77fc710d2fed798完全一致。
内容的提问来源于stack exchange,提问作者Jimbo Mahoney
相关产品推荐
相关产品推荐

