Signature algorithm generation rules
When requesting MultiExchange OpenAPI, you need to combine "appId" and "timestamp" to generate "content (appId=?×tamp=?)" and a signature as shown in the following example.
private String genSignature(String payload, String timestamp) throws GeneralSecurityException {
StringBuilder builder = new StringBuilder();
if (StringUtils.isNotBlank(payload)) {
builder.append(payload).append("&");
}
builder.append(HEADER_MERCHANT_CODE).append('=').append(this.plutoConfig.getMerchantCode()).append('&')
.append(HEADER_TIMESTAMP).append('=').append(timestamp);
// LogUtils.maskInfo("original request content:{}", builder.toString());
// do sign.
String pk = ChannelClientApolloUtils.getKmsMerchantPrivateKey();
if (StringUtils.isEmpty(pk)) {
throw new GeneralSecurityException("no merchant private key.");
}
return RsaUtil.sign(pk, builder.toString());
}
/**
@param privateKey Provided by Multiexc, held by the merchant
@param content
**/
public static String sign(String privateKey, String content) throws GeneralSecurityException {
byte[] bytes = Base64.getDecoder().decode(privateKey.getBytes());
PrivateKey pk = generatePrivateKey(bytes);
pk = generatePrivateKey(pk.getEncoded());
Signature signature = Signature.getInstance("SHA256withRSA");
signature.initSign(pk);
signature.update(content.getBytes());
return new String(Base64.getEncoder().encode(signature.sign()));
}
private static PrivateKey generatePrivateKey(byte[] bytes) throws GeneralSecurityException {
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(bytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
return keyFactory.generatePrivate(keySpec);
}
/**
* verify signature
*
* @param sourceData
* @param publicKey
* @param sign
* @return
* @throws Exception
*/
public static boolean verify(String sourceData, PublicKey publicKey, String sign) throws Exception {
byte[] keyBytes = publicKey.getEncoded();
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey key = keyFactory.generatePublic(keySpec);
Signature signature = Signature.getInstance("SHA256withRSA");
signature.initVerify(key);
signature.update(sourceData.getBytes());
return signature.verify(Base64.decodeBase64(sign.getBytes()));
}