Files
core_ng/server/util/aes.ts
T
2023-08-19 04:49:12 +00:00

43 lines
1.1 KiB
TypeScript

import { webcrypto } from "crypto";
const subtle = webcrypto.subtle;
type EncryptedData = {
iv: ArrayBuffer;
ciphertext: ArrayBuffer; //tag 포함
}
export async function AES_GCM_Encrypt(key: ArrayBuffer, msg: ArrayBuffer, aad?: ArrayBuffer): Promise<EncryptedData> {
const iv = webcrypto.getRandomValues(new Uint8Array(12));
const keyObj = await subtle.importKey("raw", key, {
name: "AES-GCM",
}, false, ["encrypt"]);
const ciphertext = await subtle.encrypt({
name: "AES-GCM",
iv,
additionalData: aad
}, keyObj, msg);
return {
iv,
ciphertext
}
}
export async function AES_GCM_Decrypt(key: ArrayBuffer, data: EncryptedData, aad?: ArrayBuffer): Promise<ArrayBuffer> {
const keyObj = await subtle.importKey("raw", key, {
name: "AES-GCM",
}, false, ["decrypt"]);
const plaintext = await subtle.decrypt({
name: "AES-GCM",
iv: data.iv,
additionalData: aad
}, keyObj, data.ciphertext);
//아마도 tag 검증 실패시 예외가 발생할 것으로 예상
return plaintext;
}