首页 服务项目 服务团队 案例展示 新闻中心 关于我们
QQ联系
电话联系
手机联系

node 生成公钥私钥加密

发布时间:2023-03-18 14:04:00
发布者:admin
浏览次数:1030

生成私钥和公钥

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:没有标签