import type { EncryptedPayload } from '../keyManagementEncryption' import { base64ToBytes, bytesToBase64 } from './encoding' import { decryptWithAesGcm, encryptWithAesGcm } from './crypto' export async function encryptPrivateKeyWithKEK(privateKey: string, kek: CryptoKey): Promise { const encoder = new TextEncoder() const plaintext = encoder.encode(privateKey) const { iv, ciphertext } = await encryptWithAesGcm({ key: kek, plaintext }) return { iv: bytesToBase64(iv), ciphertext: bytesToBase64(ciphertext) } } export async function decryptPrivateKeyWithKEK(encryptedPrivateKey: EncryptedPayload, kek: CryptoKey): Promise { const iv = base64ToBytes(encryptedPrivateKey.iv) const ciphertext = base64ToBytes(encryptedPrivateKey.ciphertext) const decrypted = await decryptWithAesGcm({ key: kek, iv, ciphertext }) const decoder = new TextDecoder() return decoder.decode(decrypted) }