我运行了您的代码,并没有发现问题。我所做的唯一改动是将modulusLength
的值调整了,因为这是密钥长度的位数表示。对于RS256算法,应设置为256 * 8 = 2048
比特。您可以将下面三个文件复制到一个文件夹中,然后运行以下命令:
npm install
npm start
index.ts
import crypto from 'crypto';
import { readFileSync, writeFileSync } from 'fs';
import { JwtPayload, sign, verify } from 'jsonwebtoken';
export function generateRSAKeyPair() {
const { privateKey, publicKey } = crypto.generateKeyPairSync('rsa', {
modulusLength: 2048,
publicKeyEncoding: { type: 'pkcs1', format: 'pem' },
privateKeyEncoding: { type: 'pkcs1', format: 'pem' }
});
return { privateKey, publicKey };
}
export function generateJWTToken(admin: boolean, username: string) {
const key = readFileSync('private.key', { encoding: 'utf-8', flag: 'r' });
return sign({
admin,
username
}, key, { algorithm: 'RS256' });
}
export function verifyJWTToken(token: string) {
const key = readFileSync('public.key', { encoding: 'utf-8', flag: 'r' });
const verifiedToken = verify(token, key, { algorithms: ['RS256'] }) as JwtPayload;
if (!verifiedToken) return false;
return verifiedToken;
}
const { privateKey, publicKey } = generateRSAKeyPair();
writeFileSync('./private.key', privateKey);
writeFileSync('./public.key', publicKey);
const token = generateJWTToken(true, 'john doe');
console.log(token);
const result = verifyJWTToken(token);
console.log(`验证结果为: ${JSON.stringify(result)}`);
package.json
{
"name": "示例",
"version": "1.0.0",
"description": "",
"main": "index.ts",
"scripts": {
"start": "tsx ./index.ts"
},
"dependencies": {
"@types/node": "^20.11.0",
"jsonwebtoken": "^9.0.2",
"tsx": "^4.7.0",
"typescript": "^5.3.3"
}
}
tsconfig.json
{
"compilerOptions": {
"strict": true,
"target": "ES2022",
"lib": ["ES2022"],
"module":"ES2022",
"moduleResolution": "Node",
"allowSyntheticDefaultImports": true,
"sourceMap": false
},
"include": [
"*.ts"
],
"exclude": [
"node_modules"
]
}