UNPKG

expresscheckout-nodejs

Version:

Juspay's official expresscheckout-nodejs sdk

89 lines 3.2 kB
import crypto from 'crypto'; import Utils from './Utils.js'; import JuspayCryptoError from './JuspayCryptoError.js'; function encrypt(data, keyId, publicKey) { try { var headers = { alg: 'RSA-OAEP', enc: 'A256GCM', cty: 'JWT', kid: keyId }; var aad = Utils.encodeBase64Url(JSON.stringify(headers)); var cek = crypto.randomBytes(32); var cekOptions = { key: publicKey, padding: crypto.constants.RSA_PKCS1_OAEP_PADDING }; var encryptedKey = Utils.encodeBase64UrlFromBuffer(crypto.publicEncrypt(cekOptions, cek)); var iv = crypto.randomBytes(12); var cipher = crypto.createCipheriv('aes-256-gcm', cek, iv); cipher.setAutoPadding(false); cipher.setAAD(Buffer.from(aad)); var cipherOutput = Buffer.concat([cipher.update(data), cipher.final()]); var authTag = cipher.getAuthTag(); var ivText = Utils.encodeBase64UrlFromBuffer(iv); var cipherText = Utils.encodeBase64UrlFromBuffer(cipherOutput); var tagText = Utils.encodeBase64UrlFromBuffer(authTag); return { header: aad, encryptedKey: encryptedKey, iv: ivText, encryptedPayload: cipherText, tag: tagText }; } catch (error) { throw new JuspayCryptoError(error, 'EncryptionFailed'); } } function decrypt(cipher, privateKey) { var data; if (typeof cipher == 'string') { try { data = JSON.parse(cipher); } catch (error) { var cipherParts = cipher.split('.'); if (cipherParts.length != 5) { throw new JuspayCryptoError('Encrypted Payload Illformed!', 'EncryptedCipherIllformed'); } data = { header: cipherParts[0], encryptedKey: cipherParts[1], iv: cipherParts[2], encryptedPayload: cipherParts[3], tag: cipherParts[4] }; } } else { data = cipher; } try { var aad = Buffer.from(data.header), encryptedKey = Utils.decodeBase64UrlToBuffer(data.encryptedKey), iv = Utils.decodeBase64UrlToBuffer(data.iv), encryptedPayload = Utils.decodeBase64UrlToBuffer(data.encryptedPayload), tag = Utils.decodeBase64UrlToBuffer(data.tag); var cekOptions = { key: privateKey, oaepHash: 'sha256', padding: crypto.constants.RSA_PKCS1_OAEP_PADDING }; var cek = crypto.privateDecrypt(cekOptions, encryptedKey); var decipher = crypto.createDecipheriv('aes-256-gcm', cek, iv); decipher.setAutoPadding(false); decipher.setAAD(aad); decipher.setAuthTag(tag); var cipherOutput = Buffer.concat([ decipher.update(encryptedPayload), decipher.final(), ]); return Utils.decodeBase64Url(cipherOutput.toString('base64')); } catch (error) { throw new JuspayCryptoError(error, 'DecryptionFailed'); } } export default { encrypt: encrypt, decrypt: decrypt }; //# sourceMappingURL=JWE.js.map