1

我一直在尝试通过里亚尔生成密钥,但由于某些原因,东西与我在 python 中看到的不同。

Python代码:

# Import required Python libraries
import time
import base64
import hashlib
import hmac

# Decode API private key from base64 format displayed in account management
api_secret = base64.b64decode("FRs+gtq09rR7OFtKj9BGhyOGS3u5vtY/EdiIBO9kD8NFtRX7w7LeJDSrX6cq1D8zmQmGkWFjksuhBvKOAWJohQ==")

# Variables (API method, nonce, and POST data)
api_path = "/0/private/TradeBalance"
api_nonce = str(int(time.time()*1000))
api_post = "nonce=" + api_nonce + "&asset=xbt"

# Cryptographic hash algorithms
api_sha256 = hashlib.sha256(api_nonce + api_post).digest()
api_hmac = hmac.new(api_secret, api_path + api_sha256, hashlib.sha512)

# Encode signature into base64 format used in API-Sign value
api_signature = base64.b64encode(api_hmac.digest())

# API authentication signature for use in API-Sign HTTP header
print(api_signature)

我设法得到的最接近的是这个(Ruby on rails):

PRIVATE_KEY = "FRs+gtq09rR7OFtKj9BGhyOGS3u5vtY/EdiIBO9kD8NFtRX7w7LeJDSrX6cq1D8zmQmGkWFjksuhBvKOAWJohQ=="

secret = Base64.decode64(PRIVATE_KEY)
path = '/0/private/TradeBalance'
nonce = DateTime.now.iso8601(6).to_time.to_i
post = "nonce=" + nonce.to_s + '&asset=xbt'

sha256 = OpenSSL::Digest::SHA256.new(nonce.to_s + post)
hmac = OpenSSL::HMAC.new(secret, path + sha256.to_s)

但是 hmac 返回:

Traceback (most recent call last):
        3: from (irb):89
        2: from (irb):89:in `new'
        1: from (irb):89:in `initialize'
RuntimeError (Unsupported digest algorithm (/0/private/TradeBalance51967c001989cf328de93113f629f71b716be83fafb38dff63aef8d970d61df7).: first num too large)

我还注意到,即使是我的 base64 解码也与 python 最初返回的不同。

4

1 回答 1

1

Ruby on Rails 还提供了一个内置函数,例如

SecureRandom.hex(64)

如果您需要一个 URL 安全的密钥,比如 API 密钥生成,Ruby 可以满足您的需求。

SecureRandom.urlsafe_base64
于 2020-07-27T07:25:23.137 回答