RSA
RSA签名示例代码
- Java
- Python
- JS
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.management.RuntimeErrorException;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
@Slf4j
public class CheckSign {
public static void main(String[] args) throws Exception {
//GET sign example
// String timestamp = "1684814440729";
// String queryString = "marginCoin=usdt&symbol=btcusdt"; // Need to be sorted in ascending alphabetical order by key
// String signContent = timestamp + "GET" + "/api/v2/mix/account/account?" + queryString;
// String sign = generate(signContent);
// log.info("sign:{}",sign);
//POST sign example
String timestamp = "1684814440729";
String preContent = timestamp + "POST" + "/api/v2/spot/trade/place-order";
String body = "{\"symbol\":\"btcusdt\",\"quantity\":\"8\",\"side\":\"buy\",\"price\":\"1\",\"orderType\":\"limit\",\"clientOid\":\"channel1233456\"}";
String signContent = preContent + body;
String sign = generate(signContent);
log.info("sign:{}",sign);
}
/**
*
* @param content: the string to be signed
* @return
*/
private String generate(String content) {
String privateKey = "-----BEGIN PRIVATE KEY-----\n" +
"xxxxxxxxxxxxxxxxxxxx9w0BAQEFAASCBKgwggSkAgEAAoIBAQD5C1iP01MC9fh5\n" +
"xxxxxxxxxxxxxxxxxxxxz6HzoSg+zd8HVxKXRTXBwMDBfLxfQXobptz1tDlPUs+g\n" +
"xxxxxxxxxxxxxxxxxxxxHxArBTimyNXX6WNL6hTw0MI238cGKiW0WvWd9v6Z6/LX\n" +
"xxxxxxxxxxxxxxxxxxxxGuvBrVIRl57FzvOPD5QKfhVxcHr63NfEViAEQfQH4IN2\n" +
"xxxxxxxxxxxxxxxxxxxxP+LXvHN7ZMiWP9bouw3r4l6v0NJ4XyucSYJL9fJ81rsI\n" +
"xxxxxxxxxxxxxxxxxxxxZKFyurE1c8XiU2aZ2qq+6vjby0ncE4dKVu5x/iJZ4gsL\n" +
"xxxxxxxxxxxxxxxxxxxxD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L7w92qi25qkAQt4sGi+QQOnHMGisak\n" +
"xxxxxxxxxxxxxxxxxxxxqiwF52M9bui5zthbWfkj4wKBgEFVT+jf235aihaS88Oj\n" +
"xxxxxxxxxxxxxxxxxxxxef7/a+gt7N1u9sEGlPspY3HuPamA39201BuItD9X83VR\n" +
"xxxxxxxxxxxxxxxxxxxx/l+ItSNUzQhX6T0cSdCo6KtmZLBQ6Zaw7r63GcdvSdR2\n" +
"xxxxxxxxxxxxxxxxxxxxxxx\n" +
"-----END PRIVATE KEY-----\n";
try {
String parsedPem = privateKey.replace("\n", "").trim();
parsedPem = parsedPem
.replace("-----BEGIN PRIVATE KEY-----", "")
.replace("-----END PRIVATE KEY-----", "");
PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64Utils.decodeFromString(parsedPem));
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PrivateKey priKey = keyFactory.generatePrivate(priPKCS8);
Signature signature = Signature.getInstance("SHA256WithRSA");
signature.initSign(priKey);
signature.update(content.getBytes(StandardCharsets.UTF_8));
String sign = Base64Utils.encodeToString(signature.sign());
return sign;
} catch (Exception ex) {
throw new RuntimeException("create sign failed", ex);
}
}
}
import base64
import json
import time
import base64
from Crypto.Hash import SHA256
from Crypto.Signature import PKCS1_v1_5
from Crypto.PublicKey import RSA
def get_timestamp():
return int(time.time() * 1000)
def rsa_sign(message, private_key):
pri_key = RSA.importKey(private_key)
encoded_param = SHA256.new(bytes(message, encoding='utf-8'))
sign_str = PKCS1_v1_5.new(pri_key).sign(encoded_param)
return base64.b64encode(sign_str).decode()
def pre_hash(timestamp, method, request_path, body):
return str(timestamp) + str.upper(method) + request_path + body
def parse_params_to_str(params):
params = [(key, val) for key, val in params.items()]
params.sort(key=lambda x: x[0])
from urllib.parse import urlencode
url = '?' +urlencode(params);
if url == '?':
return ''
return url
if __name__ == '__main__':
private_key = '''-----BEGIN PRIVATE KEY-----
XXXXXXXXXXANBgkqhkiG9w0BAQEFAASCBKgwggSk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XXXXXKBgQCxwvAl8ubNj78hsuDWgsddKIMkwvKrfdsvXrMOYouAdLjZJvjs
XXXXXXXXXXl3s9km8g/479pYlOn+Iv/Z7Lqke8/HdOFASoQ9h1nSuujgEgXUwkg1
XXXXXXXXXX0k2BY3FPnGGh8iQma1pdkUVn35fAq/m7e/S+kP1JY6lPIx1QKBgQCS
XXXXXXXXXXNmpot+ceGt2bseSd8l4jqU3nDZ0oW8+4Qnnu9QFhN4Hn9wIjpAOGaU
XXXXXXXXXXh+Vbior98JxMSDHsHmuXKPA8DishumGlqV+vxsIzLQD1Ge/dbqsERB
XXXXXXXXXXyfiyUNqjk5kcPQeHIyJk5qQaF21udoTQKBgDOMbtM0Nq7cd/SAHISR
XXXXXXXXXXAjLJW7DRJGxw3AEwxKG+nxNLeG7GsQDyPCvZSKwRpdpXRTh+6mzXqe
XXXXXXXXXXtez8Cwo6tgyKRi6QPObQk00vbrKEBTihP30m81rwBPzjwj7iKXxWgA
XXXXXXXXXXIf4qXXXXXXXXXX
-----END PRIVATE KEY-----'''
timestamp = get_timestamp()
request_path = "/api/mix/v2/order/place-order"
# POST
params = {"symbol": "TRXUSDT", "marginCoin": "USDT", "price": 0.0555, "size": 551, "side": "buy", "orderType": "limit", "force": "normal"}
body = json.dumps(params)
sign = rsa_sign(pre_hash(timestamp, "POST", request_path, str(body)), private_key)
print(sign)
# GET
body = ""
request_path = "/api/v2/mix/account/account?marginCoin=usdt&productType=USDT-FUTURES&symbol=btcusdt" # Need to be sorted in ascending alphabetical order by key
sign = rsa_sign(pre_hash(timestamp, "GET", request_path, str(body)), private_key)
print(sign)
export function sign() {
const private_key = '-----BEGIN PRIVATE KEY-----\n' +
'XXXXXXXXXXANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCdTR5gmwGH77wE\n' +
'XXXXXXXXXXVhiw7fPXWhMh7gZwurQQ8M/I9/VA8lDjwwoGuuJ6enurdfwhpZxeZH\n' +
'XXXXXXXXXXLESEXVuxJv5hdpI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fdsvXrMOYouAdLjZJvjs\n' +
'XXXXXXXXXXl3s9km8g/479pYlOn+Iv/Z7Lqke8/HdOFASoQ9h1nSuujgEgXUwkg1\n' +
'XXXXXXXXXX0k2BY3FPnGGh8iQma1pdkUVn35fAq/m7e/S+kP1JY6lPIx1QKBgQCS\n' +
'XXXXXXXXXXNmpot+ceGt2bseSd8l4jqU3nDZ0oW8+4Qnnu9QFhN4Hn9wIjpAOGaU\n' +
'XXXXXXXXXXh+Vbior98JxMSDHsHmuXKPA8DishumGlqV+vxsIzLQD1Ge/dbqsERB\n' +
'XXXXXXXXXXyfiyUNqjk5kcPQeHIyJk5qQaF21udoTQKBgDOMbtM0Nq7cd/SAHISR\n' +
'XXXXXXXXXXAjLJW7DRJGxw3AEwxKG+nxNLeG7GsQDyPCvZSKwRpdpXRTh+6mzXqe\n' +
'XXXXXXXXXXtez8Cwo6tgyKRi6QPObQk00vbrKEBTihP30m81rwBPzjwj7iKXxWgA\n' +
'XXXXXXXXXXIf4qXXXXXXXXXX\n' +
'-----END PRIVATE KEY-----\n'
const ts = Date.now();
const NodeRSA = require('node-rsa')
const pri_key = new NodeRSA(private_key)
//GET
const ts = Date.now();
const params = 'clientOid=123&coin=USDT&endTime=1659076670000&pageNo=1&pageSize=20&startTime=1659036670000' // Need to be sorted in ascending alphabetical order by key
const endpoint = '/api/v2/spot/wallet/withdrawal-records'
const method = "GET"
const pre_hash = String(ts) + method + endpoint + '?' + params
const sign = pri_key.sign(pre_hash, 'base64', 'UTF-8')
//POST
const endpoint_post = '/api/v2/spot/trade/unfilled-orders'
const params_post = '{"symbol": "BTCUSDT"}'
const method_post = "POST"
const pre_hash_post = String(ts) + method_post + endpoint_post + params_post
const sign_post = pri_key.sign(pre_hash_post, 'base64', 'UTF-8')
return sign
}