Unable to sign a file with nodejs crypto

后端 未结 1 691
余生分开走
余生分开走 2020-12-20 01:47

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\'         


        
相关标签:
1条回答
  • 2020-12-20 02:08

    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:

    • Generating a private key via the OpenSSL key generator utility or similar
    • 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);
      
    0 讨论(0)
提交回复
热议问题