Files
test-convex/generate-jwks.ts
2026-01-24 00:43:25 +08:00

40 lines
1.1 KiB
TypeScript

import * as jose from 'jose';
import fs from 'node:fs'
async function generateKeyPair() {
const { privateKey, publicKey } = await jose.generateKeyPair('RS256', {
modulusLength: 2048,
extractable: true,
});
return { privateKey, publicKey };
}
async function createJWKS(publicKey: CryptoKey) {
const jwk = await jose.exportJWK(publicKey);
// 添加 kid 字段
jwk.kid = 'kid-key-1';
const jwks = {
keys: [jwk]
};
return jwks;
}
async function main() {
const { privateKey, publicKey } = await generateKeyPair();
const jwks = await createJWKS(publicKey);
// 将私钥和 JWKS 保存到文件
const privateJWK = await jose.exportJWK(privateKey);
const privatePEM = await jose.exportPKCS8(privateKey);
const publicPEM = await jose.exportSPKI(publicKey);
fs.writeFileSync('jwt/publicKey.txt', publicPEM);
fs.writeFileSync('jwt/privateKey.txt', privatePEM);
fs.writeFileSync('jwt/privateKey.json', JSON.stringify(privateJWK, null, 2));
fs.writeFileSync('jwt/jwks.json', JSON.stringify(jwks, null, 2));
console.log('Private key and JWKS have been saved to files.');
}
main().catch(console.error);