I've created a private Key with nodejs crypto and want to sign a file with this key. My code is following:
var ecdh = crypto.createECDH('brainpoolP512t1');
ecdh.generateKeys();
var key = ecdh.getPrivateKey('buffer');
var data= fs.readFileSync(req.file.path);
var sign = crypto.createSign('sha512');
sign.update(data);
var signature = sign.sign(key, 'hex');
But I get the error:
Error: error:0906D06C:PEM routines:PEM_read_bio:no start line
at Error (native)
at Sign.sign (crypto.js:283:26)
at /....js:32:27
at Immediate.<anonymous> (/.../node_modules/multer/lib/make-middleware.js:52:37)
at runCallback (timers.js:578:20)
at tryOnImmediate (timers.js:554:5)
at processImmediate [as _immediateCallback] (timers.js:533:5)
I know it has something to do with the key format, but I don't know how to fix this. Can anyone help?
UPDATE: I edited the privateKey to fit the pem format:
var KEY_START = '-----BEGIN EC PRIVATE KEY-----\n';
var KEY_END = '\n-----END EC PRIVATE KEY-----';
const ecdh = crypto.createECDH('brainpoolP512t1');
ecdh.generateKeys();
var key =KEY_START + ecdh.getPrivateKey('base64') + KEY_END;
var data= fs.readFileSync(req.file.path);
const sign = crypto.createSign('sha512');
sign.update(data);
var signature = sign.sign(key, 'hex');
And now I geht a different error:
Error: error:0D07207B:asn1 encoding routines:ASN1_get_object:header too long
at Error (native)
at Sign.sign (crypto.js:283:26)
at /...js:37:27
at Immediate.<anonymous> (/.../node_modules/multer/lib/make-middleware.js:52:37)
at runCallback (timers.js:578:20)
at tryOnImmediate (timers.js:554:5)
at processImmediate [as _immediateCallback] (timers.js:533:5)
The key you sign the data with needs to be a valid PEM-encoded private key. The DH
getPrivateKey()
function does not return a key in this format, it returns the bare private key data.Your options include:
Using third-party node modules to properly encode the private key as outlined in RFC 5915. Full example using the
asn1.js
andbn.js
modules: