import * as jose from 'jose'; async function generateKeyPair() { const { privateKey, publicKey } = await jose.generateKeyPair('RS256', { modulusLength: 2048, extractable: true, }); return { privateKey, publicKey }; } async function createJWKS(publicKey: CryptoKey, kid?: string) { const jwk = await jose.exportJWK(publicKey); // 添加 kid 字段 jwk.kid = kid || 'kid-key-1'; const jwks = { keys: [jwk] }; return jwks; } type GenerateOpts = { kid?: string; } export const generate = async (opts: GenerateOpts = {}) => { const { privateKey, publicKey } = await generateKeyPair(); const jwks = await createJWKS(publicKey, opts.kid); // 将私钥和 JWKS 保存到文件 const privateJWK = await jose.exportJWK(privateKey); const privatePEM = await jose.exportPKCS8(privateKey); const publicPEM = await jose.exportSPKI(publicKey); return { jwks, privateJWK, privatePEM, publicPEM } }