I am implenting ALIPAY API, to my project. In order to make some request I need to generate a signature with RSA private.pem - public.pem. The documentions is only showing JAVA exemple, but I need to implement it in NodeJS. So I try using crypto.sign but cannot get this to work.
Here is the JAVA code :
const g = (content, privateKey, charset) => {
try {
PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(privateKey));
PrivateKey priKey = KeyFactory.getInstance("RSA").generatePrivate(priPKCS8);
Signature signature = Signature.getInstance("SHA256withRSA");
signature.initSign(priKey);
signature.update(content.getBytes(charset));
byte[] signed = signature.sign();
return Base64.getEncoder().encodeToString(signed);
} catch (Exception e) {
throw new RuntimeException("the key's format maybe not right");
}
}
Can any one help to convert this into NodeJS code.
HERE IS MY WORKING SOLUTIONS:
/**
* @param {*} // let parameters = new Map(); parameters.set("service", "alipay.overseas.secmerchant.maintain.queryStatus");
*/
signRSA: async (parameters) => {
let unnecessaryParams = Array.from(parameters.entries())
.filter(a1 => a1[1] === undefined || a1[1].length === 0 || a1[1] === "null")
.map(a1 => a1[0]);
unnecessaryParams.forEach(a1 => parameters.delete(a1));
let charset = ["_input_charset", "charset"].filter(a1 => parameters.has(a1)).map(a1 => parameters.get(a1))[0];
charset = charset === undefined ? "UTF-8" : charset;
//MD5,RSA,RSA2
let signContent = Array.from(parameters.entries())
.filter(a1 => {
return a1[0] !== "sign" && a1[0] !== "sign_type";
})
.sort((a1, a2) => a1[0].localeCompare(a2[0]))
.map(a1 => a1[0] + "=" + a1[1]).join("&");
let key = fs.readFileSync('./services/alipay/rsa_private_key.pem');
// let RSA_sign = r.sign_it(signContent, key, "RSA2")
let RSA_sign = crypto.createSign('RSA-SHA256')
RSA_sign.update(signContent)
let s1 = RSA_sign.sign(key, "base64")
parameters.set("sign", s1);
return Array.from(parameters.entries()).map(a1 => a1[0] + "=" + encodeURIComponent(a1[1])).join("&");
}
I've created a Node.js version of this code, it should sign content using the provided private key.
I've also created a verifySignature function to check this, and created the equivalent code in Java (using your code as a template), just to ensure we're getting the same result in both languages.
Node.js
Java