UNPKG

@gray-adeyi/korapay-sdk

Version:

A korapay client SDK for the javascript runtime.

36 lines (35 loc) 1.42 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.encryptAes256 = encryptAes256; const IV_LENGTH = 16; // deno-lint-ignore no-explicit-any async function encryptAes256(encryptionKey, data) { const iv = crypto.getRandomValues(new Uint8Array(IV_LENGTH)); const jsonData = JSON.stringify(data); const encodedData = new TextEncoder().encode(jsonData); const cryptoKey = await importKey(encryptionKey); const encryptedData = await crypto.subtle.encrypt({ name: "AES-GCM", iv }, cryptoKey, encodedData); const encryptedArray = new Uint8Array(encryptedData); const cipherText = encryptedArray.slice(0, -16); const authTag = encryptedArray.slice(-16); const ivAsHex = toHex(iv); const cipherTextAsHex = toHex(cipherText); const authTagAsHex = toHex(authTag); return `${ivAsHex}:${cipherTextAsHex}:${authTagAsHex}`; } function toHex(byteArray) { return Array.from(byteArray).map((byte) => byte.toString(16).padStart(2, "0")) .join(""); } function toUint8Array(value) { const len = value.length; const bytes = new Uint8Array(len); for (let i = 0; i < len; i++) { bytes[i] = value.charCodeAt(i); } return bytes; } async function importKey(encryptionKey) { const rawKey = toUint8Array(encryptionKey); return await crypto.subtle.importKey("raw", rawKey, { name: "AES-GCM" }, false, ["encrypt"]); }