4

in short, I want to sign a string("a") just like openssl using crypto library in node. but I get wrong output over and over again.

Long Description

signing with openssl

I have two generated rsa keys : public-key.pem and private-key.pem that I have made them with openssl :

$ openssl genrsa 2048 > private-key.pem
$ openssl rsa -in private-key.pem -pubout >public-key.pem

when I type these in shell:

$ echo "a" | openssl dgst -sha256 -sign private-key.pem >signature_openssl.bin

It generates a file named siganture_openssl.bin.

signing with node crypto

const crypto = require('crypto')
const sign = crypto.createSign('SHA256')
const fs = require('fs')
const privateKey = fs.readFileSync('./private-key.pem', 'utf8')

sign.write("a")
sign.end()
let res = sign.sign(privateKey, 'binary')
fs.writeFileSync('./signature_node.bin', res, 'binary')

this block generates a file named signature_node.bin.

verifying generated binaries

to verify generated signatues, I do:

$ echo "a" | openssl dgst -sha256 -signature signature_openssl.bin -verify public-key.pem
Verified OK

but node doesn't verify :

$ echo "a" | openssl dgst -sha256 -signature signature_node.bin -verify public-key.pem
Verification Failure

the question is: what am I doing wrong?!

Soorena
  • 4,352
  • 5
  • 30
  • 42
  • 6
    In node you signed a string consisting of the letter a, but in OpenSSL you both signed and are trying to verify a string consisting of the letter a PLUS A NEWLINE. That is different data, and the purpose of a signature is to verify the same data but not different data. Assuming non-ancient Unix, try `printf %s "a"` (you don't actually need the quotes in this case but may in others). PS: you've misspelled the `signature_` filenames two different ways, but I assume that's just a mistake in posting and your actual files are correct. – dave_thompson_085 Dec 31 '17 at 11:16
  • 1
    @dave_thompson_085 thank you that solved my problem. If you answer the question I will accept it as the right answer. – Soorena Dec 31 '17 at 11:29
  • 1
    Use `echo -n` unless you want the newline. Or, add a newline to your Node.js code. On Linux the newline is `LF`. Also see [`echo` command](http://pubs.opengroup.org/onlinepubs/009695399/utilities/echo.html). – jww Jan 01 '18 at 04:53
  • 1
    [OpenSSL create SHA hash from shell stdin](https://stackoverflow.com/q/11066171/608639), [OpenSSL string decryption issue](https://stackoverflow.com/q/17117687/608639), [Encrypt a string using openssl command line](https://stackoverflow.com/q/10106771/608639), etc. – jww Jan 01 '18 at 05:01

0 Answers0