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\'
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
and bn.js
modules:
var crypto = require('crypto');
var asn1 = require('asn1.js');
var BN = require('bn.js');
function toOIDArray(oid) {
return oid.split('.').map(function(s) {
return parseInt(s, 10)
});
}
// Define ECPrivateKey from RFC 5915
var ECPrivateKey = asn1.define('ECPrivateKey', function() {
this.seq().obj(
this.key('version').int(),
this.key('privateKey').octstr(),
this.key('parameters').explicit(0).objid().optional(),
this.key('publicKey').explicit(1).bitstr().optional()
);
});
// Generate the DH keys
var ecdh = crypto.createECDH('brainpoolP512t1');
ecdh.generateKeys();
// Generate the PEM-encoded private key
var pemKey = ECPrivateKey.encode({
version: new BN(1),
privateKey: ecdh.getPrivateKey(),
// OID for brainpoolP512t1
parameters: toOIDArray('1.3.36.3.3.2.8.1.1.14')
}, 'pem', { label: 'EC PRIVATE KEY' });
// Sign data
var sign = crypto.createSign('sha512');
sign.update('hello world');
var signature = sign.sign(pemKey, 'hex');
console.log('signature', signature);