UNPKG

pulsar_sdk_js

Version:

A convenient way for you to interact with Pulsar's Third Party APIs, using typified classes.

43 lines (42 loc) 1.47 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.encryptMessage = void 0; const publicKey_1 = require("./publicKey"); async function importPublicKey(pem) { const pemContents = pem.replace(/-----[^-]+-----/g, ''); const binaryDerString = window.atob(pemContents); const binaryDer = str2ab(binaryDerString); return window.crypto.subtle.importKey('spki', binaryDer, { name: 'RSA-OAEP', hash: 'SHA-256', }, true, ['encrypt']); } function str2ab(str) { const buf = new ArrayBuffer(str.length); const bufView = new Uint8Array(buf); for (let i = 0, strLen = str.length; i < strLen; i++) { bufView[i] = str.charCodeAt(i); } return buf; } async function encryptMessage(message) { const publicKey = await importPublicKey(publicKey_1.publicKeyPem); const enc = new TextEncoder(); const encodedMessage = enc.encode(message); try { const encrypted = await window.crypto.subtle.encrypt({ name: 'RSA-OAEP', }, publicKey, encodedMessage); const buffer = new Uint8Array(encrypted); let binary = ''; for (let i = 0; i < buffer.byteLength; i++) { binary += String.fromCharCode(buffer[i]); } return Buffer.from(binary, 'binary').toString('base64'); } catch (err) { console.error('Encryption error:', err); throw err; } } exports.encryptMessage = encryptMessage;