Skip to content

Commit

Permalink
feat: createAesKey 추가
Browse files Browse the repository at this point in the history
  • Loading branch information
elegantcoder committed Jan 2, 2024
1 parent ff91f8f commit 5bd1d3e
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 3 deletions.
8 changes: 8 additions & 0 deletions src/crypto-util/crypto-util.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand Down
25 changes: 22 additions & 3 deletions src/crypto-util/crypto-util.ts
Original file line number Diff line number Diff line change
@@ -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<Uint8Array> => {
Expand All @@ -14,6 +21,18 @@ export namespace CryptoUtil {
return crypto.getRandomValues(new Uint8Array(bytes));
};

export const createAesKey = async (length: 128 | 192 | 256): Promise<Uint8Array> => {
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);
Expand Down

0 comments on commit 5bd1d3e

Please sign in to comment.