D
Deno

help

Where to store this key — and how?

TMTimo Martinson7/22/2023
const cryptoKey =
await crypto.subtle.generateKey({
name: 'HMAC', hash: 'SHA-512'
}, true, ['sign', 'verify'])
const cryptoKey =
await crypto.subtle.generateKey({
name: 'HMAC', hash: 'SHA-512'
}, true, ['sign', 'verify'])
I want to use it with JWTs
Aahdingshier7/28/2023
You could export the key to/as Base64:
async function generateKeyAsBase64() {
const key = await crypto.subtle.generateKey(
{ name: "HMAC", hash: "SHA-512" },
true,
["sign", "verify"],
);
const keyBuffer = await crypto.subtle.exportKey("raw", key);
return btoa(String.fromCharCode(...new Uint8Array(keyBuffer)));
}
async function generateKeyAsBase64() {
const key = await crypto.subtle.generateKey(
{ name: "HMAC", hash: "SHA-512" },
true,
["sign", "verify"],
);
const keyBuffer = await crypto.subtle.exportKey("raw", key);
return btoa(String.fromCharCode(...new Uint8Array(keyBuffer)));
}
Then, e.g., store the base64 string in an environment variable. Converting the string to a key is simple:
async function getKeyFromBase64(base64Key: string) {
const key = Uint8Array.from(atob(base64Key), (c) => c.charCodeAt(0));
return await crypto.subtle.importKey(
"raw",
key,
{ name: "HMAC", hash: "SHA-512" },
true,
["sign", "verify"],
);
}
async function getKeyFromBase64(base64Key: string) {
const key = Uint8Array.from(atob(base64Key), (c) => c.charCodeAt(0));
return await crypto.subtle.importKey(
"raw",
key,
{ name: "HMAC", hash: "SHA-512" },
true,
["sign", "verify"],
);
}
Should work on deploy as well.
NNeTT7/29/2023
I usually write the key to a .env It can then be accessed as an environment variable

Looking for more? Join the community!