2026-01-13 14:49:19 +01:00

19 lines
926 B
TypeScript

import type { EncryptedPayload } from '../keyManagementEncryption'
import { base64ToBytes, bytesToBase64 } from './encoding'
import { decryptWithAesGcm, encryptWithAesGcm } from './crypto'
export async function encryptPrivateKeyWithKEK(privateKey: string, kek: CryptoKey): Promise<EncryptedPayload> {
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<string> {
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)
}