跳到主要内容

RSA

RSA签名示例代码

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" +
"xxxxxxxxxxxxxxxxxxxxD6cF5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qi25qkAQt4sGi+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);
}
}

}

您的阅读体验如何?