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

后端 未结 9 689
逝去的感伤
逝去的感伤 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:37

    If you know how to get what you want from OpenSSL, I think it's perfectly reasonable to run OpenSSL using Node's child_process.

    var cp = require('child_process')
      , assert = require('assert')
      ;
    
    var privateKey, publicKey;
    publicKey = '';
    cp.exec('openssl genrsa 2048', function(err, stdout, stderr) {
      assert.ok(!err);
      privateKey = stdout;
      console.log(privateKey);
      makepub = cp.spawn('openssl', ['rsa', '-pubout']);
      makepub.on('exit', function(code) {
        assert.equal(code, 0); 
        console.log(publicKey);
      });
      makepub.stdout.on('data', function(data) {
        publicKey += data;
      });
      makepub.stdout.setEncoding('ascii');
      makepub.stdin.write(privateKey);
      makepub.stdin.end();  
    });
    

提交回复
热议问题