Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 18 additions & 15 deletions src/lib/crypto.ts
Original file line number Diff line number Diff line change
@@ -1,28 +1,32 @@
const APP_SALT = "tryskills.sh-v1";
const ITERATIONS = 100_000;

function textToBuffer(text: string): ArrayBuffer {
return new TextEncoder().encode(text).buffer as ArrayBuffer;
// Helpers return Uint8Array<ArrayBuffer> (not SharedArrayBuffer-backed) so they
// satisfy WebCrypto BufferSource in both Node and jsdom realms.

function textToBytes(text: string): Uint8Array<ArrayBuffer> {
return new Uint8Array(new TextEncoder().encode(text));
}

function bufferToHex(buffer: ArrayBuffer): string {
return Array.from(new Uint8Array(buffer))
function bytesToHex(bytes: Uint8Array | ArrayBuffer): string {
const view = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
return Array.from(view)
.map((b) => b.toString(16).padStart(2, "0"))
.join("");
}

function hexToBuffer(hex: string): ArrayBuffer {
function hexToBytes(hex: string): Uint8Array<ArrayBuffer> {
const bytes = new Uint8Array(hex.length / 2);
for (let i = 0; i < hex.length; i += 2) {
bytes[i / 2] = parseInt(hex.substring(i, i + 2), 16);
}
return bytes.buffer as ArrayBuffer;
return bytes;
}

export async function deriveKey(userId: string): Promise<CryptoKey> {
const keyMaterial = await crypto.subtle.importKey(
"raw",
textToBuffer(userId),
textToBytes(userId),
"PBKDF2",
false,
["deriveKey"],
Expand All @@ -31,7 +35,7 @@ export async function deriveKey(userId: string): Promise<CryptoKey> {
return crypto.subtle.deriveKey(
{
name: "PBKDF2",
salt: textToBuffer(APP_SALT),
salt: textToBytes(APP_SALT),
iterations: ITERATIONS,
hash: "SHA-256",
},
Expand All @@ -46,9 +50,8 @@ export async function encrypt(
plaintext: string,
key: CryptoKey,
): Promise<{ ciphertext: string; iv: string }> {
const ivArray = crypto.getRandomValues(new Uint8Array(12));
const iv = ivArray.buffer as ArrayBuffer;
const encoded = textToBuffer(plaintext);
const iv = crypto.getRandomValues(new Uint8Array(12));
const encoded = textToBytes(plaintext);

const encrypted = await crypto.subtle.encrypt(
{ name: "AES-GCM", iv },
Expand All @@ -57,8 +60,8 @@ export async function encrypt(
);

return {
ciphertext: bufferToHex(encrypted),
iv: bufferToHex(iv),
ciphertext: bytesToHex(encrypted),
iv: bytesToHex(iv),
};
}

Expand All @@ -68,9 +71,9 @@ export async function decrypt(
key: CryptoKey,
): Promise<string> {
const decrypted = await crypto.subtle.decrypt(
{ name: "AES-GCM", iv: hexToBuffer(iv) },
{ name: "AES-GCM", iv: hexToBytes(iv) },
key,
hexToBuffer(ciphertext),
hexToBytes(ciphertext),
);

return new TextDecoder().decode(decrypted);
Expand Down