How to create a pair private/public keys using Node.js crypto?

后端 未结 9 642
逝去的感伤
逝去的感伤 2020-12-23 01:59

I have to generate two keys (private and public) to encrypt a text with the public and let the user with the private key decrypt the text.

Is it possible with the mo

相关标签:
9条回答
  • 2020-12-23 02:17

    I have not used it, but this may be useful:

    http://ox.no/posts/diffie-hellman-support-in-node-js

    Documentation is severely lacking on this (no examples that I could find).

    0 讨论(0)
  • 2020-12-23 02:20

    child_process route is a terrible and non-scalable solution imo. Stay away.

    I chose to go with keypair instead.

    0 讨论(0)
  • 2020-12-23 02:21

    You can use this rsa-json module. It just spawns a openssl process, so it is pretty dependent on the OS (it does not work by default on windows).

    0 讨论(0)
  • 2020-12-23 02:22
    const crypto = require('crypto');
    
      const { privateKey, publicKey } = crypto.generateKeyPairSync('rsa', {
        modulusLength: 2048,
        publicKeyEncoding: {
          type: 'spki',
          format: 'pem'
        },
        privateKeyEncoding: {
          type: 'pkcs8',
          format: 'pem'
        }
      }); 
    
    0 讨论(0)
  • 2020-12-23 02:25

    Use the crypto module from npm to generate KeyPair.

    var crypto = require('crypto');
    
    var prime_length = 60;
    var diffHell = crypto.createDiffieHellman(prime_length);
    
    diffHell.generateKeys('base64');
    console.log("Public Key : " ,diffHell.getPublicKey('base64'));
    console.log("Private Key : " ,diffHell.getPrivateKey('base64'));
    
    console.log("Public Key : " ,diffHell.getPublicKey('hex'));
    console.log("Private Key : " ,diffHell.getPrivateKey('hex'));
    

    Above is a example snippet. To know more checkout documentation http://nodejs.org/api/crypto.html

    0 讨论(0)
  • 2020-12-23 02:27

    nodejs v10.12 now supports this natively with crypto.generateKeyPair

    const { generateKeyPair } = require('crypto');
    generateKeyPair('rsa', {
      modulusLength: 4096,
      publicKeyEncoding: {
        type: 'spki',
        format: 'pem'
      },
      privateKeyEncoding: {
        type: 'pkcs8',
        format: 'pem',
        cipher: 'aes-256-cbc',
        passphrase: 'top secret'
      }
    }, (err, publicKey, privateKey) => {
      // Handle errors and use the generated key pair.
    });
    
    0 讨论(0)
提交回复
热议问题