21 lines
1.1 KiB
TypeScript
21 lines
1.1 KiB
TypeScript
import type { EncryptedPayload } from '../keyManagementEncryption'
|
|
import { base64ToBytes, bytesToBase64 } from './encoding'
|
|
import { decodeKekBytesFromStorage, decryptWithAesGcm, deriveKeyFromPhrase, encodeKekBytesForStorage, encryptWithAesGcm, exportKEK, importKEK } from './crypto'
|
|
|
|
export async function encryptKEK(kek: CryptoKey, recoveryPhrase: string[]): Promise<EncryptedPayload> {
|
|
const phraseKey = await deriveKeyFromPhrase(recoveryPhrase)
|
|
const kekBytes = await exportKEK(kek)
|
|
const plaintext = encodeKekBytesForStorage(kekBytes)
|
|
const { iv, ciphertext } = await encryptWithAesGcm({ key: phraseKey, plaintext })
|
|
return { iv: bytesToBase64(iv), ciphertext: bytesToBase64(ciphertext) }
|
|
}
|
|
|
|
export async function decryptKEK(encryptedKEK: EncryptedPayload, recoveryPhrase: string[]): Promise<CryptoKey> {
|
|
const phraseKey = await deriveKeyFromPhrase(recoveryPhrase)
|
|
const iv = base64ToBytes(encryptedKEK.iv)
|
|
const ciphertext = base64ToBytes(encryptedKEK.ciphertext)
|
|
const decrypted = await decryptWithAesGcm({ key: phraseKey, iv, ciphertext })
|
|
const kekBytes = decodeKekBytesFromStorage(decrypted)
|
|
return importKEK(kekBytes)
|
|
}
|