UNPKG

expresscheckout-nodejs

Version:

Juspay's official expresscheckout-nodejs sdk

66 lines 2.24 kB
import crypto from 'crypto'; import Utils from './Utils.js'; import JuspayCryptoError from './JuspayCryptoError.js'; function sign(claims, keyId, privateKey) { try { var signer = crypto.createSign('RSA-SHA256'); var signatureHeader = '{"alg":"RS256","kid":"' + keyId + '"}'; var header = Utils.encodeBase64Url(signatureHeader); var payload = Utils.encodeBase64Url(claims); var data = "".concat(header, ".").concat(payload); signer.update(data); var signedBuffer = signer.sign(privateKey); var signed = Utils.encodeBase64UrlFromBuffer(signedBuffer); return { header: header, payload: payload, signature: signed }; } catch (error) { throw new JuspayCryptoError(error); } } // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-explicit-any function verify(signed, publicKey) { try { var data = void 0; if (typeof signed == 'string') { try { data = JSON.parse(signed); } catch (error) { var signedParts = signed.split('.'); if (signedParts.length != 3) { throw new JuspayCryptoError('Signature Illformed', 'SignedPayloadIllformed'); } data = { header: signedParts[0], payload: signedParts[1], signature: signedParts[3] }; } } else { data = signed; } var verifier = crypto.createVerify('RSA-SHA256'); var protect = "".concat(data.header, ".").concat(data.payload); verifier.update(protect); var isVerified = verifier.verify(publicKey, data.signature, 'base64'); if (isVerified) { return Utils.decodeBase64Url(data.payload); } else { throw new JuspayCryptoError('Signature verification failed', 'SignatureValidationFailed'); } } catch (error) { throw new JuspayCryptoError(error); } } export default { sign: sign, verify: verify }; //# sourceMappingURL=JWS.js.map