Skip to main content

RSA

RSA Signature Demo Code

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/spot/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" +
"xxxxxxxxxxxxxxx9Tcqfz6HzoSg+zd8HVxKXRTXBwMDBfLxfQXobptz1tDlPUs+g\n" +
"xxxxxxxxxxxxxxxBaZ5qHxArBTimyNXX6WNL6hTw0MI238cGKiW0WvWd9v6Z6/LX\n" +
"xxxxxxxxxxxxxxxcO7EKGuvBrVIRl57FzvOPD5QKfhVxcHr63NfEViAEQfQH4IN2\n" +
"xxxxxxxxxxxxxxx4jILUP+LXvHN7ZMiWP9bouw3r4l6v0NJ4XyucSYJL9fJ81rsI\n" +
"xxxxxxxxxxxxxxx4RSsFZKFyurE1c8XiU2aZ2qq+6vjby0ncE4dKVu5x/iJZ4gsL\n" +
"xxxxxxxxxxxxxxxCggEAD6cF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kAQt4sGi+QQOnHMGisak\n" +
"xxxxxxxxxxxxxxxzsXqDqiwF52M9bui5zthbWfkj4wKBgEFVT+jf235aihaS88Oj\n" +
"xxxxxxxxxxxxxxxHlYCIef7/a+gt7N1u9sEGlPspY3HuPamA39201BuItD9X83VR\n" +
"xxxxxxxxxxxxxxxZn1O8/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);
}
}

}