【问题标题】:API secret generation in railsRails 中的 API 秘密生成
【发布时间】:2020-08-25 18:26:32
【问题描述】:

我一直在尝试通过 rias 生成密钥,但由于某些原因,我在 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 最初返回的不同。

【问题讨论】:

标签: ruby-on-rails api rest kraken.com


【解决方案1】:

Ruby on Rails 还提供了类似的内置函数

SecureRandom.hex(64)

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

SecureRandom.urlsafe_base64

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-14
    • 2019-11-14
    • 2022-12-23
    • 2014-08-23
    • 2019-07-27
    • 2014-03-07
    • 2015-02-21
    • 2018-09-30
    相关资源
    最近更新 更多