mirror of
https://github.com/oven-sh/bun
synced 2026-02-09 18:38:55 +00:00
* Add bun-types to packages * Improve typing * Fix types in tests * Fix dts tests * Run formatter * Fix all type errors * Add strict mode, fix type errors * Add ffi changes * Move workflows to root * Add workflows * Remove labeler * Add child_process types * Fix synthetic defaults issue * Remove docs * Move scripts * Run prettier * Include examples in typechecking * captureStackTrace types * moved captureStackTrace types to globals * Address reviews Co-authored-by: Colin McDonnell <colinmcd@alum.mit.edu> Co-authored-by: Dylan Conway <dylan.conway567@gmail.com>
84 lines
2.1 KiB
TypeScript
84 lines
2.1 KiB
TypeScript
import { describe, expect, it } from "bun:test";
|
|
|
|
describe("Web Crypto", () => {
|
|
it("has globals", () => {
|
|
expect(crypto.subtle !== undefined).toBe(true);
|
|
expect(CryptoKey.name).toBe("CryptoKey");
|
|
expect(SubtleCrypto.name).toBe("SubtleCrypto");
|
|
});
|
|
it("should encrypt and decrypt", async () => {
|
|
const key = await crypto.subtle.generateKey(
|
|
{
|
|
name: "AES-GCM",
|
|
length: 256,
|
|
},
|
|
true,
|
|
["encrypt", "decrypt"],
|
|
);
|
|
const iv = crypto.getRandomValues(new Uint8Array(12));
|
|
const data = new TextEncoder().encode("Hello World!");
|
|
const encrypted = await crypto.subtle.encrypt(
|
|
{
|
|
name: "AES-GCM",
|
|
iv,
|
|
},
|
|
key,
|
|
data,
|
|
);
|
|
const decrypted = await crypto.subtle.decrypt(
|
|
{
|
|
name: "AES-GCM",
|
|
iv,
|
|
},
|
|
key,
|
|
encrypted,
|
|
);
|
|
expect(new TextDecoder().decode(decrypted)).toBe("Hello World!");
|
|
});
|
|
|
|
it("should verify and sign", async () => {
|
|
async function importKey(secret) {
|
|
return await crypto.subtle.importKey(
|
|
"raw",
|
|
new TextEncoder().encode(secret),
|
|
{ name: "HMAC", hash: "SHA-256" },
|
|
false,
|
|
["sign", "verify"],
|
|
);
|
|
}
|
|
|
|
async function signResponse(message, secret) {
|
|
const key = await importKey(secret);
|
|
const signature = await crypto.subtle.sign(
|
|
"HMAC",
|
|
key,
|
|
new TextEncoder().encode(message),
|
|
);
|
|
|
|
// Convert ArrayBuffer to Base64
|
|
return btoa(String.fromCharCode(...new Uint8Array(signature)));
|
|
}
|
|
|
|
async function verifySignature(message, signature, secret) {
|
|
const key = await importKey(secret);
|
|
|
|
// Convert Base64 to Uint8Array
|
|
const sigBuf = Uint8Array.from(atob(signature), (c) => c.charCodeAt(0));
|
|
|
|
return await crypto.subtle.verify(
|
|
"HMAC",
|
|
key,
|
|
sigBuf,
|
|
new TextEncoder().encode(message),
|
|
);
|
|
}
|
|
|
|
const msg = `hello world`;
|
|
const SECRET = "secret";
|
|
const signature = await signResponse(msg, SECRET);
|
|
|
|
const isSigValid = await verifySignature(msg, signature, SECRET);
|
|
expect(isSigValid).toBe(true);
|
|
});
|
|
});
|