UNPKG

@simplito/privmx-webendpoint

Version:

PrivMX Web Endpoint library

64 lines (63 loc) 1.96 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.encryptWithAES256GCM = encryptWithAES256GCM; exports.decryptWithAES256GCM = decryptWithAES256GCM; exports.isEncryptionSuccess = isEncryptionSuccess; exports.isDecryptionSuccess = isDecryptionSuccess; async function encryptWithAES256GCM(key, iv, data, header) { try { const cryptoKey = await ensureCryptoKey(key, "encrypt"); // Encrypt the data const encrypted = await crypto.subtle.encrypt({ name: "AES-GCM", iv: iv, additionalData: header, tagLength: 128, // 16 bytes * 8 = 128 bits (TAG_LEN equivalent) }, cryptoKey, data); // The encrypted result contains both ciphertext and authentication tag return { success: true, data: new Uint8Array(encrypted), }; } catch (error) { return { success: false, error: "EncryptionFailed", }; } } async function decryptWithAES256GCM(key, iv, encryptedData, header) { try { const cryptoKey = await ensureCryptoKey(key, "decrypt"); const decrypted = await crypto.subtle.decrypt({ name: "AES-GCM", iv: iv, additionalData: header, tagLength: 128, }, cryptoKey, encryptedData); return { success: true, data: new Uint8Array(decrypted), }; } catch (error) { return { success: false, error: "DecryptionFailed", }; } } // Type guard functions for better type safety function isEncryptionSuccess(result) { return result.success; } function isDecryptionSuccess(result) { return result.success; } async function ensureCryptoKey(key, usage) { if (key instanceof CryptoKey) { return key; } return crypto.subtle.importKey("raw", key, { name: "AES-GCM" }, false, [usage]); }