导入所需库:
import forge from 'node-forge';
生成密钥:
async function generateKey(type:string='RSA', digit:number=2048) {
const key={privateKey:'',publicKey:''}
switch(type){
case 'RSA': {
try {
const keyPair = forge.pki.rsa.generateKeyPair({ bits: digit });
key.privateKey = forge.pki.privateKeyToPem(keyPair.privateKey);
key.publicKey = forge.pki.publicKeyToPem(keyPair.publicKey);
} catch (error) {
console.error('Error generating keys:', error);
}
break;
}
default: break;
}
return key;
}
参数1位密钥类型,应为”RSA”;参数2为生成密钥位数,默认为2048;
返回值为包含 privateKey 和 publicKey 的对象;
注意: 密钥生成时间一般较久,可能需要做一些相应的处理来优化用户体验。