NodeJS 如何使用crypto模块使用公钥-私钥对进行加密和解密?

rqqzpn5f  于 2023-04-05  发布在  Node.js
关注(0)|答案(3)|浏览(533)

我必须使用crypto模块在Node js中编写代码(因为我不允许使用MIT许可之外的任何模块)。我需要生成一个密钥对,并使用公钥加密一些消息,然后使用私钥解密它。第一部分即密钥对的生成已经完成。我没有得到任何线索如何使用crypto模块使用相同的密钥对加密和解密一些消息。

bwitn5fc

bwitn5fc1#

这应该可以满足您的需要:

const { generateKeyPairSync, publicEncrypt, privateDecrypt } = require('crypto');

//generate a key pair RSA type encryption with a .pem format
const { publicKey, privateKey } = generateKeyPairSync('rsa', {
  modulusLength: 4096,
  publicKeyEncoding: {
    type: 'spki',
    format: 'pem'
  },
  privateKeyEncoding: {
    type: 'pkcs8',
    format: 'pem',

  }
});

// print out the generated keys
console.log(`PublicKey: ${publicKey}`);
console.log(`PrivateKey: ${privateKey}`);

//message to be encrypted
var toEncrypt = "my secret text to be encrypted";
var encryptBuffer = Buffer.from(toEncrypt);

//encrypt using public key
var encrypted = publicEncrypt(publicKey,encryptBuffer);

//print out the text and cyphertext
console.log("Text to be encrypted:");
console.log(toEncrypt);
console.log("cipherText:");
console.log(encrypted.toString());

//decrypt the cyphertext using the private key
var decryptBuffer = Buffer.from(encrypted.toString("base64"), "base64");
var decrypted = privateDecrypt(privateKey,decryptBuffer);

//print out the decrypted text
console.log("decripted Text:");
console.log(decrypted.toString());

它生成可用于加密和解密消息的密钥对。

dhxwm5r4

dhxwm5r42#

在Crypto库的节点文档中有以下示例:

var crypto = require('crypto');
var alice = crypto.getDiffieHellman('modp5');
var bob = crypto.getDiffieHellman('modp5');

alice.generateKeys();
bob.generateKeys();

var alice_secret = alice.computeSecret(bob.getPublicKey(), null, 'hex');
var bob_secret = bob.computeSecret(alice.getPublicKey(), null, 'hex');

/* alice_secret and bob_secret should be the same */
console.log(alice_secret == bob_secret);

此示例显示如何计算共享secret,然后可以与.createCipher().createDecipher()一起使用,如下所示:

var encrypt64 = function(aMsg, aSecret) {
  var cipher, tRet;
  cipher = crypto.createCipher('aes-256-cbc', aSecret);
  tRet = cipher.update(aMsg, 'utf8', 'base64');
  tRet += cipher.final('base64');
  return tRet;
};

var decrypt64 = function(aMsg, aSecret) {
  var decipher, tRet;
  decipher = crypto.createDecipher('aes-256-cbc', aSecret);
  tRet = decipher.update(aMsg.replace(/\s/g, "+"), 'base64', 'utf8');
  tRet += decipher.final('utf8');
  return tRet;
};
n6lpvg4x

n6lpvg4x3#

该解决方案:

  • 创建公钥-私钥对
  • 将这些密钥导出到文件
  • 打开公钥文件并使用它加密文本并将其保存到文件中
  • 打开私钥文件并使用它来解密加密的文本文件

所有数据都转换为base64字符串,以便在Web上轻松传递这些值。
这是我在消化这个过程时所寻找的。

'use strict';

import crypto from 'crypto';
import fs from 'fs';

// Make public/private RSA key pair
let keyPair = await crypto.subtle.generateKey(
  {
    name: "RSA-OAEP",
    modulusLength: 4096,
    publicExponent: new Uint8Array([1, 0, 1]),
    hash: "SHA-512",
  },
  true,
  ["encrypt", "decrypt"]
);

// export public key as base64 string and save to file
const exportedPublicKey = await crypto.subtle.exportKey('spki', keyPair.publicKey);
const expPublicKeyBase64 = Buffer.from(exportedPublicKey).toString('base64');
fs.writeFileSync('./publickey.txt', expPublicKeyBase64);

// export private key as base64 string and save to file
const exportedPrivateKey = await crypto.subtle.exportKey('pkcs8', keyPair.privateKey);
const exportedPrivateKeyBase64 = Buffer.from(exportedPrivateKey).toString('base64');
fs.writeFileSync('./privatekey.txt', exportedPrivateKeyBase64);

// import and make public key from base64 file
const publicKeyBase64Buffer = fs.readFileSync('./publickey.txt');
const publicKeyBase64String = Buffer.from(publicKeyBase64Buffer).toString('ascii');
const publicKeyBuffer = Buffer.from(publicKeyBase64String, 'base64');
const publicCryptoKey = await crypto.subtle.importKey(
  'spki',
  publicKeyBuffer,
  { name: 'RSA-OAEP', hash: "SHA-512" },
  false,
  ["encrypt"]
);

// encrypt some plaintext using public key, convert to base64, and save to file
const plainText = 'abc';
const plainTextUInt8 = (new TextEncoder()).encode(plainText);
const cypherTextBuffer = await crypto.subtle.encrypt(
  { name: "RSA-OAEP", hash: "SHA-512" },
  publicCryptoKey,
  plainTextUInt8
);
const cypherTextBase64 = Buffer.from(cypherTextBuffer).toString('base64');
fs.writeFileSync('./cypherText.txt', cypherTextBase64);

// import and make private key from base64 file
const privateKeyBase64Buffer = fs.readFileSync('./privatekey.txt');
const privateKeyBase64String = Buffer.from(privateKeyBase64Buffer).toString('ascii');
const privateKeyBuffer = Buffer.from(privateKeyBase64String, 'base64');
const privateCryptoKey = await crypto.subtle.importKey(
  'pkcs8',
  privateKeyBuffer,
  { name: 'RSA-OAEP', hash: "SHA-512" },
  false,
  ["decrypt"]
);

// open base64 encrypted file and decrypt using private key
const cypherTxtBase64Buffer = fs.readFileSync('./cypherText.txt');
const cypherTxtBase64String = Buffer.from(cypherTxtBase64Buffer).toString('ascii');
const cypherTxtBuffer = Buffer.from(cypherTxtBase64String, 'base64');
const plainTxtBuff = await crypto.subtle.decrypt('RSA-OAEP', privateCryptoKey, cypherTxtBuffer);
const plainTxt = Buffer.from(plainTxtBuff).toString('ascii');
console.log(plainTxt);

相关问题