UNPKG

sinch-rtc

Version:

RTC JavaScript/Web SDK

95 lines 3.23 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Codec = void 0; const CryptoJS = require("crypto-js"); const api_1 = require("../ocra/api"); const _1 = require("./"); const models_1 = require("./models"); /** * Encrypt and decrypts MXP messages and clients */ class Codec { /** * Method that encodes MXP message using random IV. Should produce different output for every invocation. * @param payload - payload string * @param key - user encryption key */ static encrypt(payload, key) { const iv = CryptoJS.lib.WordArray.random(16); return this.encodeWithIV(payload, key, iv); } /** * Private method that encodes MXP message with possiblity of injecting IV * @param payload - payload string * @param key - user encryption key * @param iv - initialization vector */ static encodeWithIV(payload, key, iv) { const bytes = CryptoJS.lib.WordArray.create([]); const unencrypted = CryptoJS.enc.Utf8.parse(payload); const cipher = CryptoJS.AES.encrypt(unencrypted, key.key, { iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7, }); bytes.concat(iv); bytes.concat(cipher.ciphertext); return CryptoJS.enc.Base64.stringify(bytes); } /** * Method that decodes MXP message * @param encryptedPayload - raw data in base64 format * @param key - user encryption key */ static decrypt(encryptedPayload, key) { const packet = CryptoJS.enc.Base64.parse(encryptedPayload); const iv = CryptoJS.lib.WordArray.create(packet.words.slice(0, 4)); const cipherText = CryptoJS.lib.WordArray.create(packet.words.slice(4)); const parsedCipherText = CryptoJS.enc.Base64.stringify(cipherText); const decrypted = CryptoJS.AES.decrypt(parsedCipherText, key.key, { iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7, }); return decrypted.toString(CryptoJS.enc.Utf8).trim(); } /** * Serializes the data in client * @param client - */ static encodeClient(client) { const model = { fs: client.channel, fc: client.cli, fd: client.deviceDescription, fi: client.instanceId, fu: client.userId, }; return new models_1.Body(models_1.Body.clientType, JSON.stringify(model)); } /** * Parses stringified client data * @param body - */ static decodeClient(body) { if (body.type !== models_1.Body.clientType) { throw new _1.MXPError(_1.MXPError.Codes.INVALID_BODY_TYPE); } try { const model = JSON.parse(body.data); return { userId: model.fu, channel: model.fs, cli: model.fc, deviceDescription: model.fd, instanceId: model.fi, domain: api_1.Domain.Mxp, }; } catch (e) { throw new _1.MXPError(_1.MXPError.Codes.BODY_PARSE_FAIL); } } } exports.Codec = Codec; //# sourceMappingURL=Codec.js.map