QuantumQ
Denoโ€ข3y agoโ€ข
25 replies
Quantum

How do I make the crypto.subtle.digest algo flexible?

This is a learning moment, bear with me. ๐Ÿ˜…

I can hard code an algo for the digest like this:
const algo = "SHA-256";
const d = new Uint8Array(
    await crypto.subtle.digest(
        algo, new TextEncoder().encode("test")
    )
);


But if I want to make the algo flexible, it forces me to make it a DigestAlgorithm and it cannot be a string shown here:
async function digest(algo: string): Promise<Uint8Array> {
    return new Uint8Array(
        await crypto.subtle.digest(
            algo, new TextEncoder().encode("test")
        )
    );
}


I reviewed what that is in the source:
https://github.com/denoland/deno_std/blob/main/crypto/_wasm/mod.ts

I see this:
export type DigestAlgorithm = typeof digestAlgorithms[number];
(I don't quite see what is going on here and am interested.)

Bottom line is, when I make algo:string a algo:DigestAlgorithm in the digest function param list, it stops complaining, but I need to have some calling code somewhere be a flexible string (or maybe an enum if necessary) that somehow translates to a DigestAlgorithm for this to work.

I've been struggling with this. Any ideas?
Was this page helpful?