0

When i load the ECDH private key with the crypto module i am getting the following error:

node:internal/crypto/diffiehellman:231
  this[kHandle].setPrivateKey(key);
                ^

RangeError: Private key is not valid for specified curve.
    at ECDH.setPrivateKey (node:internal/crypto/diffiehellman:231:17)
......
  code: 'ERR_CRYPTO_INVALID_KEYTYPE'
}

The private key was created executing openssl ecparam -name prime256v1 -genkey -noout -out "private_key.pem"

I tried the following:

// private_key.pem
-----BEGIN EC PRIVATE KEY-----
MHcCAQEEIDuwn+0qX7ZDCOjQPxBNNn9nr/OLWptW+kwlJcb60q4EoAoGCCqGSM49
AwEHoUQDQgAEV8swcnlrvUuuQ1M9iyLiGfSuAkC2xJa6gK3wQyemV3LsiflS5bDw
ce4oSTzRtVfyFElm3jv0pKxMj7uK7/YCMA==
-----END EC PRIVATE KEY-----
// index.js

// Libraries
const crypto = require('crypto');
const fs = require('fs');


const ecdh = new crypto.createECDH('prime256v1')
ecdh.setPrivateKey(fs.readFileSync('./private_key.pem'), 'utf8')
  • `setPrivateKey()` expects the private EC key as raw key (32 bytes for prime256v1) and not as PEM encoded key in SEC1 format. You can get the raw private key from the PEM key using an ASN.1 parser, e.g. https://lapo.it/asn1js/. – Topaco Apr 23 '23 at 19:54
  • If you prefer to do the conversion PEM to raw with a library, see [here](https://stackoverflow.com/a/74950235/9014097). – Topaco Apr 23 '23 at 20:01
  • Thaks @Topaco. Is there any native nodejs module for this? Does support this conversion the crypto module? – Andres Umaña Apr 23 '23 at 20:59
  • Because for example the eckey-utils returns Invalid or unsupported PEM content also with the pem examples in their npm package. https://www.npmjs.com/package/eckey-utils – Andres Umaña Apr 23 '23 at 21:16
  • *...Is there any native nodejs module for this? Does support this conversion the crypto module?...*: No. – Topaco Apr 23 '23 at 21:30
  • *...Because for example the eckey-utils returns Invalid or unsupported PEM content also with the pem examples in their npm package...*: I cannot reproduce this. Works for me both with the key from the documentation and with your key. Must be a problem specific to your environment. – Topaco Apr 23 '23 at 21:31
  • Checking the library https://github.com/tibetty/eckey-utils/blob/master/index.js, looks like there is a issue with the regex for EC key pems. If i replace ([^]+) by ([\s\S]+?) everything works fine. – Andres Umaña Apr 24 '23 at 01:17
  • Works for me locally and here https://replit.com/@3hK8cL8H24hwiS7/TeemingFittingMetadata#index.js without any fix. Tested with v 0.7.13 (but haven't looked at the source code closely). – Topaco Apr 24 '23 at 07:03

0 Answers0