0

I need to encrypt (and decrypt) a string with a public key previously generated in nodejs (i'm using version 0.12) with crypto module, but i'm unable to do it.

For first i generated the keys in this way:

var diffHell = crypto.createDiffieHellman(60);
diffHell.generateKeys('base64');
var publicKey = diffHell.getPublicKey('base64'); //or whatever 'hex','binary'
var privateKey = diffHell.getPrivateKey('base64'); //or whatever 'hex','binary'

Then i tried to encrypt a string using the generated public key:

crypto.publicEncrypt({key: publicKey}, new Buffer(textToEncrypt));

Running this snippet, node throw this error:

Error: error:0906D06C:PEM routines:PEM_read_bio:no start line
    at Error (native)
    at Object.exports.publicEncrypt (crypto.js:362:18)
    [...]

Reading it, I understand that the key must be in PEM format, but i can't find in the documentation how to tranform a public key in PEM.

So, How i can do that? Someone has done this yet?

gdg
  • 587
  • 1
  • 3
  • 10

2 Answers2

1

Diffie-Hellman (Key Exchange) is an algorithm and protocol to derive a shared secret based on modular arithmetic. It is not a public-key cipher in the same way as RSA is. You cannot use Diffie-Hellman for crypto.publicEncrypt().

Node.js' Crypto module doesn't provide a way to generate a public-private RSA key pair, so you either need to use OpenSSL through child_process or use one of the many modules which provide this sort of thing (e.g. ursa).

Community
  • 1
  • 1
Artjom B.
  • 61,146
  • 24
  • 125
  • 222
  • I know the existence of of ursa, but if possible i prefer to not use third-party modules for this scenario. What I need is an asymmetric encription, there's no method to do it with standard libraries? – gdg Mar 12 '15 at 10:46
0

You do not need to uses ursa for key generation. Instead you can generate keys with openssl then store the generated PEM keys on your server and try to load them in your script

abedfar
  • 1,989
  • 24
  • 21