node 生成公鑰私鑰加密
發(fā)布時(shí)間:2023-03-18 14:04:00
發(fā)布者:admin
瀏覽次數(shù):1028
生成私鑰和公鑰
const { generateKeyPairSync } = require('crypto');
const { publicKey, privateKey } = generateKeyPairSync('rsa', {
modulusLength: 4096,
publicKeyEncoding: {
type: 'spki',
format: 'pem'
},
privateKeyEncoding: {
type: 'pkcs8',
format: 'pem',
cipher: 'aes-256-cbc',
passphrase: 'top secret'
}
});
公鑰加密,私鑰解密
const crypto = require('crypto');
const fs = require('fs');
const publicKey = fs.readFileSync('./app/controller/publicKey.pem');
const privateKey = fs.readFileSync('./app/controller/privateKey.pem');
const secret = JSON.stringify({ a: 1 });
const encrypt = crypto.publicEncrypt(publicKey, Buffer.from(secret));
console.log(encrypt);
const decrypt = crypto.privateDecrypt({ key: privateKey, passphrase: '1233211234567' }, encrypt);
console.log(JSON.parse(decrypt.toString()));
TAGS:沒(méi)有標(biāo)簽