简体   繁体   English

如何使用 nodejs 使用密码短语加密私钥和公钥?

[英]How do I encrypt a private and public key with a pass phrase using nodejs?

I want to get a function that generates public and private keys and then these keys can be encrypted in a plain text.我想得到一个生成公钥和私钥的 function,然后这些密钥可以用明文加密。 In my case I managed to encrypt the plaintext with those keys, but it is the opposite of what I am trying to achieve.在我的例子中,我设法用这些密钥加密了明文,但这与我想要实现的相反。

This is what I have working, but I want to do just the opposite.这就是我的工作,但我想做相反的事情。 Encrypt the keys with a plaintext or pass phrase.使用明文或密码短语加密密钥。

"use strict";

// Requires NodeJS >= 11.6.0

const crypto = require("crypto"); const util = require("util");

const generateKeyPair = util.promisify(crypto.generateKeyPair);

async function main() {
const exportOptions = {
    format: "pem",
    type: "pkcs1"
};

const { privateKey, publicKey } = await generateKeyPair("rsa", {
    modulusLength: 2048,
});

const plainText = "PRUEBA"; //Texto X a cifrar
const cipherText = crypto.publicEncrypt(publicKey, Buffer.from(plainText)); //Buffer is encrypted by the key

//console.log("Keys: ")
//console.log(publicKey.export(exportOptions)); // Public Key not encrypted
//console.log(privateKey.export(exportOptions)); // Private Key not encrypted

console.log("Plain text:", plainText); //Este es nuestro Pass Phrase
console.log("Cipher text:", cipherText.toString("hex")); 

const decrypted = crypto.privateDecrypt(privateKey, cipherText).toString(); 
console.log("Decrypted:", decrypted);
console.log("Success: ", decrypted === plainText);

}

main();

This is what i tried.这是我试过的。

"use strict";

// Requires NodeJS >= 11.6.0

const crypto = require("crypto"); const util = require("util");

const generateKeyPair = util.promisify(crypto.generateKeyPair);

async function main() {
const exportOptions = {
    format: "pem",
    type: "pkcs1"
};

const { privateKey, publicKey } = await generateKeyPair("rsa", {
    modulusLength: 2048,
});

console.log(publicKey.export(exportOptions)); // Public Key not encrypted
console.log(privateKey.export(exportOptions)); // Private Key not encrypted

const plainText = "PRUEBA"; //Pass phrase 
var clavePublica = publicKey.export(exportOptions);

console.log("Prueba",clavePublica);
const cipherText = crypto.publicEncrypt(plainText, clavePublica); //Encrypt "clavePublica" with plainText
//const cipherText = crypto.publicEncrypt(Buffer.from(plainText),Buffer.from(publicKey) );
//console.log("Keys: ")
//console.log("Plain text:", plainText); //Este es nuestro Pass Phrase
//console.log("Cipher text:", cipherText.toString("hex")); //Texto X cifrado

//const plainText2 = "PRUEBA2";
//const decrypted = crypto.privateDecrypt(privateKey, cipherText).toString(); //Texto X descifrado
//console.log("Decrypted:", decrypted);
//console.log("Success: ", decrypted === plainText);
}

main();

This is the result:这是结果:

-----BEGIN RSA PUBLIC KEY-----
MIIBCgKCAQEAwCs5V1/qCqdLxgh/LBfhkLr4HF0Z7s9Bq2//fq4YEQ0lNgouYHfg
wEohDjTInJ/l7kOVkxoDknopJrc7Jac3in5y37o5yO7bThhg8/tpoZL/KT6FoDXt
0PH+o7qq2aSgYU/qJkfLl5DTViwHBDbE/A9byr9frV7+CWDA7i4nMe3692FA+xYv
nRbJ1OinEaDIts7YMJHfJJxHb0SNSrohof1Zqx5DOxs9T5JHHiC8XwSTfebilR+i
LVQPwevX9/ZLzU7FYbMSBiqYbaUp/VQ/4SBd2IE1naKTd/8mWgUPqn1DoOjC907T
h0zfkif+/RSR7lgtZ9t5IjlBoBOrOTI82QIDAQAB
-----END RSA PUBLIC KEY-----

-----BEGIN RSA PRIVATE KEY-----
MIIEogIBAAKCAQEAwCs5V1/qCqdLxgh/LBfhkLr4HF0Z7s9Bq2//fq4YEQ0lNgou
YHfgwEohDjTInJ/l7kOVkxoDknopJrc7Jac3in5y37o5yO7bThhg8/tpoZL/KT6F
oDXt0PH+o7qq2aSgYU/qJkfLl5DTViwHBDbE/A9byr9frV7+CWDA7i4nMe3692FA
+xYvnRbJ1OinEaDIts7YMJHfJJxHb0SNSrohof1Zqx5DOxs9T5JHHiC8XwSTfebi
lR+iLVQPwevX9/ZLzU7FYbMSBiqYbaUp/VQ/4SBd2IE1naKTd/8mWgUPqn1DoOjC
907Th0zfkif+/RSR7lgtZ9t5IjlBoBOrOTI82QIDAQABAoIBABr0NR0coUQ7R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SWUDlEBpwk9RAl8Lr6daLrsnSQNNCrVYnRPg06DOCInu
9X5mrZWkht+Ou8ILhgfpwdm23ObIv3KI5oZ4tX43g5aIuF8yiUQVo4WDPFo9n8dD
jlDOAYOhAGa6+MOfgSpyaU5eBIZl+tkD/F4w1yQ1LVU1yjGMfFo=
-----END RSA PRIVATE KEY-----

node:internal/crypto/cipher:79
    return method(data, format, type, passphrase, buffer, padding, oaepHash,
           ^

Error: error:1E08010C:DECODER routines::unsupported
    at Object.publicEncrypt (node:internal/crypto/cipher:79:12)
    at main (C:\Users\mmorena\Oracle Content - Accounts\Oracle Content\Escritorio\Comu BC\PubyPriv.js:28:31) {
  library: 'DECODER routines',
  reason: 'unsupported',
  code: 'ERR_OSSL_UNSUPPORTED'
}

Node.js v18.12.0

You just need to add the "passphrase" key in your options object.您只需要在选项 object 中添加“密码”键。

Here is some code (assuming that you already have your keys & node crypto imported):这是一些代码(假设您已经导入了密钥和节点加密):

const publicKey = ... // Public key
const privateKey = ... //Private key
const options = {
    type:"pkcs1",
    format:"pem",
    passphrase:"YOUR PASSPHRASE"
}
const exportedPublic = publicKey.export(options);
const exportedPrivate = privateKey.export(options);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用 NodeJS 中的公钥仅加密 JSON 有效负载的选定值? - How do I encrypt only selected values of a JSON payload using a public key in NodeJS? 如何使用java生成的public加密nodejs中的字符串 - How do I encrypt string in nodejs with public generated by java 是否可以在NodeJS中生成密钥对,使用公共密钥在PHP中加密数据以及在NodeJS中解密? - Can I generate a key-pair in NodeJS, encrypt data in PHP using the public key, and decrypt in NodeJS? 如何在Node.js中使用openssl生成公钥/私钥对? - How to generate Public/Private key pairs using openssl in nodejs? 如何使用 Hyperledger Fabric 中生成的 ECDSA 私钥和公钥进行加密和解密 - How to encrypt and decrypt using ECDSA private key and public key generated in Hyperledger fabric 如何在NodeJ中进行基于X或Y-of-X公钥的加密/解密? - How to do 1-of-X or Y-of-X public key based encrypt/ decrypt in NodeJs? 我已经通过 Java spring 安全性生成了公钥,我尝试使用该公钥来使用 Nodejs Crypto 加密数据,但它返回错误 - I had generate Public Key by Java spring security and I try to use that public key to encrypt data with Nodejs Crypto but it return error 如何在node.js中创建用于签名数据的公钥和私钥? - How do I create a public and private key in node.js for signing data? 仅使用 nodejs/javascript 从私钥 pem 中提取公钥 - Extract public key from private key pem using only nodejs/javascript 使用RSA公钥加密字符串 - Using RSA public key to encrypt a string
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM