diff --git a/src/crypto-util/crypto-util.spec.ts b/src/crypto-util/crypto-util.spec.ts index c3afc76..6a05fa1 100644 --- a/src/crypto-util/crypto-util.spec.ts +++ b/src/crypto-util/crypto-util.spec.ts @@ -22,6 +22,14 @@ describe('CryptoUtil', () => { }); }); + describe('createAesKey', () => { + it('should return a Uint8Array', async () => { + const result = await CryptoUtil.createAesKey(256); + expect(result).toBeInstanceOf(Uint8Array); + expect(result.length).toBe(32); + }); + }); + describe('encodeBase64', () => { it('should accept string and return a base64 encoded string', () => { const result = CryptoUtil.encodeBase64('hello world'); diff --git a/src/crypto-util/crypto-util.ts b/src/crypto-util/crypto-util.ts index 7c634b0..7b0b8e8 100644 --- a/src/crypto-util/crypto-util.ts +++ b/src/crypto-util/crypto-util.ts @@ -1,6 +1,13 @@ -// eslint-disable-next-line @typescript-eslint/ban-ts-comment -// @ts-ignore -const crypto: any = globalThis.crypto; +import type { webcrypto } from 'crypto'; + +declare global { + namespace globalThis { + // eslint-disable-next-line no-var + var crypto: typeof webcrypto; + } +} + +const crypto = globalThis.crypto; export namespace CryptoUtil { export const sha256 = async (data: string | Uint8Array): Promise => { @@ -14,6 +21,18 @@ export namespace CryptoUtil { return crypto.getRandomValues(new Uint8Array(bytes)); }; + export const createAesKey = async (length: 128 | 192 | 256): Promise => { + const key = await crypto.subtle.generateKey( + { + name: 'AES-GCM', + length: length, + }, + true, + ['encrypt', 'decrypt'] + ); + return new Uint8Array(await crypto.subtle.exportKey('raw', key)); + }; + export const encodeBase64 = (data: Uint8Array | string): string => { if (typeof data === 'string') { data = new TextEncoder().encode(data);