Max
Max

Reputation: 1459

How do I sign w/ private key in Node.js

I'm trying to do the equivalent for the following PHP function

openssl_private_encrypt

to use my private key to sign a string

Here's what I'm doing

var signer = crypto.createSign('RSA-SHA256').update(timestamp + '|' + userId);
var signature = signer.sign(privKey, 'base64');

My first question is what does it mean when RSA and SHA256 are put together? I understand what it means to encrypt something with RSA private key, or to hash something using SHA256. But I can't comprehend what it means to have those two together.

I put it there because createSign requires a string parameter, ("RSA" is not supported), and RSA-SHA256 is the closest thing I found.

My second question is how do I

openssl_private_encrypt

in Node.js?

Upvotes: 4

Views: 1927

Answers (1)

Maarten Bodewes
Maarten Bodewes

Reputation: 94088

Normal signing operations consist of a hash calculation, which is then (if required for the function) and then encrypted by the private key. The hash is the compressed - smaller - representation of the message, for which no duplicate hashes (collisions) can be found. For RSA the message is then padded using a scheme found in PKCS#1 v2.1 (public standard), after which modular exponentiation is performed.

The modular exponentiation is often incorrectly called encryption, encryption requires a different padding method for RSA (and hashing is not performed for encryption either).

You should not use openssl_private_encrypt to sign a string, it is a deprecated function, mainly required for relatively particular authentication purposes. When used on its own it encrypts the data using the padding used for signing, but it does leave out the hash and the hash indicator.

To create an equivalent for openssl_private_encrypt you need to be able to perform the PKCS#1 v1.5 padding method and modular exponentiation. You can probably retrieve those functions from the source code of Node.js, it's unlikely you will find them in a higher level API. You are however advised to do away with the openssl_private_encrypt function in PHP and use a higher level signature function.

Upvotes: 3

Related Questions