How to generate JWK for a NestedKey? #683
Replies: 1 comment
-
This is what I ended up with: // Mainly from https://github.com/panva/jose/issues/112
import type { Jsonable } from "@/api/routes";
import {
compactDecrypt,
CompactEncrypt,
generateKeyPair,
jwtVerify,
SignJWT,
type GenerateKeyPairResult,
} from "jose";
import { forceDefined } from "..";
const textEncoder = new TextEncoder();
let keypairWrapper: GenerateKeyPairResult | undefined;
let keypairInner: GenerateKeyPairResult | undefined;
export const encode = async (content: Jsonable): Promise<string> => {
keypairWrapper ??= await generateKeyPair("ES256", {
crv: "P-256",
extractable: true,
modulusLength: 2048,
});
// Create a signed JWT
const jwt = await new SignJWT({})
.setSubject(JSON.stringify(content))
.setIssuedAt()
.setIssuer(forceDefined(process.env.NEXT_PUBLIC_BASE_URL))
// .setExpirationTime("5m")
.setProtectedHeader({
alg: "ES256",
// kid: jwk.kid,
})
.sign(keypairWrapper.privateKey);
keypairInner ??= await generateKeyPair("RSA-OAEP-256", {
extractable: true,
modulusLength: 2048,
});
const jwe = await new CompactEncrypt(textEncoder.encode(jwt))
.setProtectedHeader({
alg: "RSA-OAEP-256",
enc: "A256GCM",
})
.encrypt(keypairInner.publicKey);
return jwe;
};
const textDecoder = new TextDecoder();
export const decode = async (jwe: string): Promise<Jsonable> => {
keypairInner ??= await generateKeyPair("RSA-OAEP-256", {
extractable: true,
modulusLength: 2048,
});
// decrypt the JWE
const { plaintext: decryptedJwt } = await compactDecrypt(
jwe,
keypairInner.privateKey
);
keypairWrapper ??= await generateKeyPair("ES256", {
crv: "P-256",
extractable: true,
modulusLength: 2048,
});
const { payload } = await jwtVerify(
textDecoder.decode(decryptedJwt),
keypairWrapper.publicKey
);
return payload.sub !== undefined ? JSON.parse(payload.sub) : null;
}; |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
I'm following #112 about encoding / decoding a NestedKey
It works super well with the provided keys 👍
I'm not very knowledgeable in the encryption topic... After looking around the Doc / examples I could not figure out how to generate the 4(?) JWK, when I go to https://www.googleapis.com/oauth2/v3/certs as some example do I only get 2 keys
Questions:
Here is my whole code if that helps future devs
Code for encode/decode
Usage of previous code:
Beta Was this translation helpful? Give feedback.
All reactions