Skip to content

Instantly share code, notes, and snippets.

@masad-frost
Created June 2, 2025 13:01
Show Gist options
  • Save masad-frost/7eaa901e7ed0a180f770fec072c09485 to your computer and use it in GitHub Desktop.
Save masad-frost/7eaa901e7ed0a180f770fec072c09485 to your computer and use it in GitHub Desktop.
import { bench, run } from 'mitata';
import { createCipheriv, createDecipheriv, randomBytes } from 'crypto';
const keyBuffer = randomBytes(32);
const ivBuffer = randomBytes(12);
const text = 'hello world';
const textBuffer = Buffer.from(text, 'utf8');
function encryptNative() {
const cipher = createCipheriv('aes-256-gcm', keyBuffer, ivBuffer);
const encrypted = Buffer.concat([cipher.update(textBuffer), cipher.final()]);
const tag = cipher.getAuthTag();
return { encrypted, tag };
}
function decryptNative({ encrypted, tag }: { encrypted: Buffer; tag: Buffer }) {
const decipher = createDecipheriv('aes-256-gcm', keyBuffer, ivBuffer);
decipher.setAuthTag(tag);
const decrypted = Buffer.concat([decipher.update(encrypted), decipher.final()]);
return decrypted;
}
const subtleKey = await crypto.subtle.importKey(
'raw',
keyBuffer,
{ name: 'AES-GCM' },
false,
['encrypt', 'decrypt']
);
const encoder = new TextEncoder();
const encodedText = encoder.encode(text);
async function encryptWeb() {
return await crypto.subtle.encrypt(
{ name: 'AES-GCM', iv: ivBuffer },
subtleKey,
encodedText
);
}
async function decryptWeb(encrypted: ArrayBuffer) {
return await crypto.subtle.decrypt(
{ name: 'AES-GCM', iv: ivBuffer },
subtleKey,
encrypted
);
}
bench('node:crypto', () => {
const { encrypted, tag } = encryptNative();
decryptNative({ encrypted, tag });
});
bench('crypto.subtle', async () => {
const encrypted = await encryptWeb();
await decryptWeb(encryptedWeb);
});
await run();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment