其實不光是bitmex,現在主流的數字貨幣交易網站都是採用類似的API認證方式,因此,本篇文章其實是適用於火幣,OKEX等其他交易所的簽名生成的
數字貨幣交易所的API安全認證
securityDefinitions":{"apiKey":{"type":"apiKey","in":"header","name":"api-key"},"apiSignature":{"type":"apiKey","in":"header","name":"api-signature"},"apiExpires":{"type":"apiKey","in":"header","name":"api-expires"}},"security":[{"apiKey":[],"apiSignature":[],"apiExpires":[]}]}
一般來說都是3個值需要配置:
- api-expires: 本次API調用的有效時間,超過該時間調用失效,避免重放攻擊
- api-key: 與你的
api-secret
是一個pair對,一一對應,知道了api-key
即可查詢到api-secret
- api-signature:
api-secret
和message
一起生成的簽名,這裏的message
一般包括:- verb
- url
- nonce
- data
舉例:'POST/api/v1/order1416993995705{"symbol":"XBTZ14","quantity":1,"price":395.01}'
,如果是GET
,沒有body的話,則data爲''
api-signature
的生成規則一般爲:
hmac_sha256
,輸出值需轉化爲 hex
這裏,假設我們有一組KEY和SECRET:
API_KEY = “096oNuabZ57u9IozHP9vdpOx”
API_SECRET = “hqMMxKBYtYJ2bLQayvxVd3aqPXEz_KVIHImqq17oTbzmmVBJ”
python 實現
import hashlib
import hmac
from future.builtins import bytes
secret = bytes("hqMMxKBYtYJ2bLQayvxVd3aqPXEz_KVIHImqq17oTbzmmVBJ",'utf8')
message = bytes('POST/api/v1/order1416993995705{"symbol":"XBTZ14","quantity":1,"price":395.01}','utf8')
print(hmac.new(secret,message, digestmod=hashlib.sha256).hexdigest())
輸出爲:
a0719c00dbd3f5a3bcdd5a63af1473e7c5cfbd3fd504eae8a6cdbf3938a7821f
nodejs 實現
先定義同樣的變量:
let secret = "hqMMxKBYtYJ2bLQayvxVd3aqPXEz_KVIHImqq17oTbzmmVBJ";
let message = 'POST/api/v1/order1416993995705{"symbol":"XBTZ14","quantity":1,"price":395.01}';
crypto
var crypto = require('crypto');
console.log(crypto.createHmac('sha256', secret).update(message).digest('hex'));
輸出爲:
a0719c00dbd3f5a3bcdd5a63af1473e7c5cfbd3fd504eae8a6cdbf3938a7821f
crypto-js
var CryptoJS = require('crypto-js')
console.log(CryptoJS.enc.Hex.stringify(CryptoJS.HmacSHA256(message,secret)) )
這裏特別注意,CryptoJS.HmacSHA256的參數順序,message在前面,secret在後面
輸出爲:
a0719c00dbd3f5a3bcdd5a63af1473e7c5cfbd3fd504eae8a6cdbf3938a7821f