node.js rsa加解密

0 人评论
  作者: Avrit   分类:学习   浏览:304
Node自带加解密的库crypto,不用安装第三方库就能实现加解密

util.js:

const fs = require('fs');
const path = require('path');
const crypto = require('crypto');

function generateKeys() {
  const { publicKey, privateKey } = crypto.generateKeyPairSync('rsa', {
    modulusLength: 4096,
    publicKeyEncoding: {
      type: 'pkcs1',
      format: 'pem',
    },
    privateKeyEncoding: {
      type: 'pkcs1',
      format: 'pem',
      cipher: 'aes-256-cbc',
      passphrase: '',
    },
  });
  fs.writeFileSync('private.cer', privateKey);
  fs.writeFileSync('public.cer', publicKey);
}

function encrypt(plain, pathToPublicKey) {
  const publicKey = fs.readFileSync(path.resolve(__dirname, pathToPublicKey), 'utf8');
  const buffer = Buffer.from(plain, 'utf8');
  return crypto.publicEncrypt(publicKey, buffer).toString('base64');
}

function decrypt(cipher, pathToPrivateKey) {
  const privateKey = fs.readFileSync(path.resolve(__dirname, pathToPrivateKey), 'utf8');
  const buffer = Buffer.from(cipher, 'base64');
  const plain = crypto.privateDecrypt({
    key: privateKey.toString(),
    passphrase: ''
  }, buffer);
  return plain.toString('utf8')
}


module.exports = {
  generateKeys,
  encrypt,
  decrypt
};
index.js:

const { generateKeys, encrypt, decrypt } = require('./utils');

generateKeys();
const cypher = encrypt('hello', 'public.cer');
console.log(cypher);
const plain = decrypt(cypher, 'private.cer');
console.log(plain);
输出:

> node index.js

VDWO5U8gdNmbS5/euzhr/Yx8NC8HBkHR40obxMm+EtnXXw2dq+ojmbet1mxYg/x8mSrkMHV6a+zbmjkF0y9XP7euZnNJug1SiDCgfTF2ctcjjnJVWREsuub/JORcIHTqpHLnYCBuCyceazP5KFyJk1IRSDev09/8Hn5wWjLzcOHEU/qR5QANFPQ0
skyQqRhvkyKwWLSODosycJebqrC8xvfcFPpDSRUe64qNv5EIU/sB9RYfqbjNa5psyVrcjnaL7oSPDwINxtlqNcL6a3D1GKOdJJWbluuxllKEia9m1tsufpoh4abvigIFCBXWrTuMKHQuBbBifRWjQdFbqlLkb6aTvlzHDiCbuYg0FU3jEps7FSwk
utOjREDRMCmCAsoMt8trJuP9hkpZa4q18o3YLKvGYQLwFrbw5WrWSauAuxTz9Wb7T9WZXJOgrP+bymB7rwZxMvBhkXxtQtbB8kuGwoXu6o6e/0mXKsaaOKzQs9g7EyrUwVs8ane5J1OI9n5F76MfPWbz0NbfbIwRv0V2HoSAvJY+oWPrYjvyPkou
0KwsnmG9egSGCIkglqyrbfQ1pmLoxzOzjFrrKEpkXWuN9NZv8Inucb87VcDr23XkLo72Rh05mYn8YSECF/2GIREcDadU+gVSaoRl2v+K+iv4XYeePg/M4SVCsj4oc0aAgaE=
hello