I am trying to send envelopes from Docusign using only Apps Script.
function createJWT(){
const header = {
alg: 'RS256',
typ: 'JWT',
};
const now = Date.now();
const expires = new Date(now);
expires.setHours(expires.getHours() + 1);
const payload = {
exp: Math.round(expires.getTime() / 1000),
iat: Math.round(now / 1000),
iss: "integrator key",
sub: "user id",
aud: "url",
scope: "scopes"
};
var toSign = Utilities.base64EncodeWebSafe(JSON.stringify(header)) + '.' + Utilities.base64EncodeWebSafe(JSON.stringify(payload));
toSign = toSign.replace(/=+$/, '');
var privateKey = "-----BEGIN RSA PRIVATE KEY-----<private key here>-----END RSA PRIVATE KEY-----";
const signatureBytes = Utilities.computeRsaSha256Signature(
toSign,
privateKey
);
const signature = Utilities.base64EncodeWebSafe(signatureBytes);
return toSign + '.' + signature;
}
Utilities.computeRsaSha256Signature() returns:
Exception: Invalid argument: key
How can I create JWT using RSA Keypairs?
Public/Private keys from Docusign:
-----BEGIN PUBLIC KEY-----\n{public key here}\n-----END PUBLIC KEY----
------BEGIN RSA PRIVATE KEY-----\n{private key here}\n-----END RSA PRIVATE KEY-----
Use Utilities.base64Encode()
instead of Utilities.base64EncodeWebSafe()
.
Once you make that substitution remove the line with toSign.replace(...)
and you should be good to go.
UPDATE
The above fixes still apply but I think I know what your core issue is. Check out this SO thread.
Utilities.computeRsaSha256Signature()
expects a private key that starts with BEGIN PRIVATE KEY
not BEGIN RSA PRIVATE KEY
. You'll need to find a 3rd party library compatible with Google Apps Script that can compute keys of the second form (PKCS#1).