Timo Martinson
Timo Martinson12mo ago

Where to store this key — and how?

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'])
3 Replies
Timo Martinson
Timo Martinson12mo ago
I want to use it with JWTs
AhDingsHier
AhDingsHier12mo ago
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.
NeTT
NeTT12mo ago
I usually write the key to a .env It can then be accessed as an environment variable