{"name":"eckey-utils","version":"0.7.8","keywords":["ec","key","public key","private key","conversion","raw","PEM","generate","parse","ECDH","ECDSA","sign","verify"],"author":{"name":"tibetty"},"license":"ISC","_id":"eckey-utils@0.7.8","maintainers":[{"name":"tibetty","email":"xihua.duan@gmail.com"}],"homepage":"https://github.com/tibetty/eckey-utils#readme","bugs":{"url":"https://github.com/tibetty/eckey-utils/issues"},"dist":{"shasum":"f0b0bc447a1d081b49a39075fa8b76ffc1924ae5","tarball":"http://registry-npm.ywwl.com/eckey-utils/download/eckey-utils-0.7.8.tgz","fileCount":4,"integrity":"sha512-OVwEBeBTNtGMaJUnfxk8XDYYrK94Wd2skQN2ln0LEOf3XXGCHfRG5toLZVFU5WdfFOR7JcGq8He4nDGMnjPkRw==","signatures":[{"sig":"MEQCIEJUCirvRqjMFB01rUOxEGQxuXAaMc6TPRimGtat1YYrAiB/hoGWVZdQYuCnh515CqDyHu1+sFRJqZ6OcBUbFf88wA==","keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA"}],"unpackedSize":26717,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJcF0+VCRA9TVsSAnZWagAAul4P/07wS3pCKWJ3L9zvHC3A\nj0Xmttm64Pp5csp3XwwMeLC1mNJPjNYoYaAzLX0ko3RMrKUVLANWL3zYi6zF\nsG3OGb2NynmvxbWXNx8I9ARxPgRkbVAnEVQmWhDuz9lRz9e1176ujaFwHfRM\nVpd+z6zLMJ2PLINqPO8M7jcfk7Wt66GEQLJadWxhkdSEv/MxEWfQCvOFUoH5\nT4ANl1FcweBfaV+8yu8IEWT41hdgkGizkMPO9Gv+8i2ei93OWv3fDSt1GumC\nZI7rLVqaT/fE2gCzcHJJxYnbfk5HqDB50MIGKarh4huntMpwQaAGqVOkOitc\nKvfrRXw24rk5YfLFWg294DVy+GoBvq8jm5XjiXkklT76QUFpWfDVJRBd9EI0\nvG1n59iQO8Zpq0wfotYqL8WvqdS7w3pD5jGP9TEbRQQ1/87hx9kXWt8z8yFg\nR2klW7iEigWZ5GgPEDXFFxoM2GSBGK09SgSOSMhlxGENj/axUDrWgH3AyLg+\nUxR7ExbEROwJUyL/QlYJ9gm0fFdv6B1CiBxUKY8EiF6t13EBW1OWVRM4yPWu\n7ge3lQRnmUr857/R6JGSdAzT93SdOYaMUtpeDJSBYIzyNOUWHCgtNub/21EP\nCNw07SlWis7/qoR3t0+sdVmTlZMtUK8xbSEeKpAryhkM4qvTB0h5yuMn3z7V\nUBc5\r\n=DEjY\r\n-----END PGP SIGNATURE-----\r\n","size":6332,"noattachment":false,"key":"/eckey-utils/-/eckey-utils-0.7.8.tgz"},"main":"index.js","gitHead":"1fa03819b63fa3e6c57bb161cb4289a8a663d3c8","scripts":{"test":"node test.js"},"_npmUser":{"name":"tibetty","email":"xihua.duan@gmail.com"},"repository":{"url":"git+https://github.com/tibetty/eckey-utils.git","type":"git"},"_npmVersion":"6.5.0","description":"Node.js based EC key utilities that can generate PEM keys (required by crypto.sign and crypto.verify) from the raw ones usually but not necessarily generated by crypto.ECDH","directories":{},"_nodeVersion":"11.4.0","_hasShrinkwrap":false,"_npmOperationalInternal":{"tmp":"tmp/eckey-utils_0.7.8_1545031573420_0.30791753015562895","host":"s3://npm-registry-packages"},"readme":"# eckey-utils\n\n[![npm](https://img.shields.io/npm/v/eckey-utils.svg)](https://www.npmjs.com/package/eckey-utils)\n[![CI](https://github.com/tibetty/eckey-utils/actions/workflows/ci.yml/badge.svg)](https://github.com/tibetty/eckey-utils/actions/workflows/ci.yml)\n[![license](https://img.shields.io/npm/l/eckey-utils.svg)](./LICENSE)\n[![types](https://img.shields.io/badge/types-included-blue.svg)](./dist/index.d.ts)\n\nConvert raw EC key material to and from PEM, DER and JWK.\n\n`crypto.createECDH()` returns bare keys (the scalar `d` and the point `04 || x || y`), while\n`crypto.sign()` and `crypto.verify()` want a PEM string or a `KeyObject`. This library bridges the\ngap in both directions, so the same key pair can be generated raw, persisted as PEM, and parsed back\ninto raw keys.\n\n- No runtime dependencies: nothing beyond `Buffer` and `node:crypto`.\n- ESM and CommonJS builds with bundled TypeScript types.\n- 79 named curves: NIST, SEC 2 prime and binary, Brainpool, ANSI X9.62 and WAP WSG.\n- JWK support for the EC curves with a registered `crv` value (P-256, P-384, P-521, secp256k1),\n  plus OKP keys for Ed25519 and Ed448.\n- Compressed public points (`02 || x` / `03 || x`) accepted anywhere a key is read; output is always\n  uncompressed.\n- Key length checked against the curve, so a key from the wrong curve fails where it happens.\n\n## Install\n\n```bash\nnpm install eckey-utils\n```\n\nNode.js 22 or newer. CI covers 22, 24 and 26.\n\n**Node.js only.** The package uses `Buffer` and `node:crypto`, and it exists to bridge raw keys to\n`crypto.sign` / `crypto.verify`. Browsers need none of this: WebCrypto takes JWK keys directly\nthrough `crypto.subtle`, and no `browser` build is provided.\n\n## Quick start\n\nGenerate a PEM pair from raw keys and sign with it:\n\n```ts\nimport { createECDH, createSign, createVerify } from 'node:crypto';\nimport { generatePem } from 'eckey-utils';\n\nconst ecdh = createECDH('prime256v1');\necdh.generateKeys();\n\nconst { privateKey, publicKey } = generatePem('prime256v1', {\n    sk: ecdh.getPrivateKey(),\n    pk: ecdh.getPublicKey(),\n});\n\nconst message = Buffer.from('Hello, World!');\nconst signature = createSign('sha256').update(message).sign(privateKey);\n\nconst verified = createVerify('sha256').update(message).verify(publicKey, signature);\nconsole.log(verified); // true\n```\n\nParse a PEM back into raw keys:\n\n```ts\nimport { parsePem } from 'eckey-utils';\n\nconst { curveName, privateKey, publicKey } = parsePem(pem);\n// curveName === 'prime256v1', privateKey and publicKey are Buffers\n```\n\nCommonJS works the same way: `const { generatePem } = require('eckey-utils');`\n\n## API\n\n### `generatePem(input, keys?, options?)` and `generateDer(input, keys?, options?)`\n\nEncode raw keys. Both accept the same arguments and return a pair that only contains the keys you\npassed in.\n\n```ts\ngeneratePem('prime256v1', { sk, pk }); // { privateKey: '-----BEGIN EC PRIVATE KEY-----…', publicKey: '…' }\ngeneratePem({ curveName: 'prime256v1', privateKey: sk }); // { privateKey: '…' }\ngenerateDer('prime256v1', { pk }); // { publicKey: <Buffer 30 59 …> }\ngeneratePem('prime256v1', { sk, pk }, { type: 'pkcs8' }); // { privateKey: '-----BEGIN PRIVATE KEY-----…' }\ngeneratePem('prime256v1', { sk, pk }, { passphrase }); // encrypted, OpenSSL PBES2 defaults\n```\n\n| Argument  | Meaning                                                         |\n| --------- | --------------------------------------------------------------- |\n| `input`   | A curve name, or an object carrying the curve name and the keys |\n| `keys`    | Optional key material, used only for keys missing from `input`  |\n| `options` | `{ type, passphrase, cipher }` — see below                      |\n\nA compressed public point (`02 || x` or `03 || x`, SEC 1 v2 section 2.3.3) is accepted wherever a\npublic key is accepted and expanded to `04 || x || y` on the way out, so everything this library\nwrites is uncompressed. Decompression is delegated to OpenSSL through `node:crypto`, on every curve\nit implements.\n\nKey aliases accepted in either argument: `sk` / `privateKey`, `pk` / `publicKey`. Curve aliases\naccepted in the object form: `curveName` / `curve` / `crv`. A curve name can be the Node name\n(`prime256v1`) or the JWK name (`P-256`).\n\nKey material is checked against the curve before encoding: a private key must be 1 to\n`CURVE_PRIVATE_KEY_BYTES[curve]` bytes (the byte length of the curve order), and a public point must\nbe `1 + 2n` bytes uncompressed or `1 + n` bytes compressed, where `n` is `CURVE_KEY_BYTES[curve]`. A\nkey from another curve, a truncated buffer or a hex string therefore fails at the call, with the\ncurve and both sizes in the message. OpenSSL then checks the values: the public point must lie on\nthe curve, the private key must be from 1 to the curve order minus one, and when both keys are\npassed the public key must be the one the private key derives. Two curves of the same size (P-256\nand secp256k1, say) are therefore told apart as well. A private key shorter than the order, as `ECDH#getPrivateKey()`\nreturns one time in 256 on P-256, is left-padded with zeros, so PEM, DER and JWK output always\ncarries the full width that OpenSSL writes and RFC 7518 requires.\n\nThe private key is encoded as `ECPrivateKey` (RFC 5915) by default, or as PKCS#8 `PrivateKeyInfo`\n(RFC 5958) with `{ type: 'pkcs8' }`; the public key is always `SubjectPublicKeyInfo` (RFC 5480).\nWhen both keys are passed, the public key is embedded in the private key structure, as OpenSSL does.\nBoth encodings are byte-identical to what OpenSSL produces for the same key.\n\n### `parsePem(pem, options?)`\n\nParse an `EC PRIVATE KEY` (RFC 5915), `PRIVATE KEY` (PKCS#8) or `PUBLIC KEY` (RFC 5480) block into\nraw key material:\n\n```ts\n{ curveName: 'prime256v1', privateKey?: Buffer, publicKey?: Buffer }\n```\n\nLF or CRLF line endings, a UTF-8 BOM, an indented block and trailing whitespace on any line are all\naccepted, and so is text around the block (RFC 7468) and the `EC PARAMETERS` block that\n`openssl ecparam -genkey` writes ahead of the key. Content holding more than one key block is refused\nrather than guessed at. A private key that was encoded without an embedded public key parses back\nwithout `publicKey`. PEM blocks this library does not handle are named in the message.\n\nEncrypted private keys are read with a passphrase, for both containers:\n\n```ts\nparsePem(encryptedPem, { passphrase }); // legacy EC PRIVATE KEY + Proc-Type, and ENCRYPTED PRIVATE KEY\nparseSkDer(encryptedDer, { passphrase }); // PKCS#8 EncryptedPrivateKeyInfo\n```\n\nThe passphrase goes straight to OpenSSL through `node:crypto`; this library implements no part of\nPBES2. Without a passphrase an encrypted key fails with `Encrypted PEM requires a passphrase`, and\nwith a `passphrase` on unencrypted input the option is simply ignored, so one code path can read\nboth.\n\nEncrypted **output** follows OpenSSL's own parameters, so it is interchangeable with\n`openssl pkcs8 -topk8 -v2 aes-256-cbc`:\n\n```ts\ngeneratePem('prime256v1', { sk, pk }, { passphrase }); // PKCS#8 PBES2, aes-256-cbc\ngeneratePem('prime256v1', { sk, pk }, { passphrase, cipher: 'aes-128-cbc' });\ngeneratePem('prime256v1', { sk, pk }, { type: 'sec1', passphrase }); // legacy Proc-Type container\ngenerateDer('prime256v1', { sk, pk }, { passphrase }); // EncryptedPrivateKeyInfo\n```\n\nPassing `passphrase` implies `type: 'pkcs8'`; ask for `type: 'sec1'` only if you need the legacy\ncontainer, which OpenSSL still writes for `openssl ec -aes256` but which uses the weaker\n`EVP_BytesToKey` derivation. Encrypted DER is PKCS#8 only — OpenSSL cannot write SEC1 DER encrypted.\n`cipher` without `passphrase` is an error rather than a silently ignored option.\n\n### `parseSkDer(der)` and `parsePkDer(der)`\n\nThe DER-only counterparts of `parsePem`. `parseSkDer` accepts both private key structures; RFC 5915\nand PKCS#8 are told apart by their version number.\n\n### `generateJwk(input, keys?)` and `parseJwk(jwk)`\n\n```ts\nconst { privateKey, publicKey } = generateJwk('P-256', { sk, pk });\n// privateKey: { kty: 'EC', crv: 'P-256', x: '…', y: '…', d: '…', key_ops, kid }\nparseJwk(privateKey); // back to { curveName, privateKey, publicKey }\n```\n\nJWK covers the curves with a registered `crv` value: P-256, P-384 and P-521 (RFC 7518) plus\nsecp256k1 (RFC 8812). Those RFCs require `x` and `y` next to `d`; when only the private key is\npassed, the public key is derived from it through OpenSSL, and when both are passed they must\nmatch. Pass the curve either as the Node name (`secp256k1`) or as the JWK name (`P-256`).\n\n`kid` is the RFC 7638 thumbprint of the key, so both halves of a pair carry the same `kid` and\ndifferent keys never share one.\n\n### Errors\n\nEvery error is a plain `Error` with a message naming the problem, for example:\n\n| Message                                      | Cause                                      |\n| -------------------------------------------- | ------------------------------------------ |\n| `Curve name is not optional`                 | No curve name was passed                   |\n| `Unsupported elliptic curve: foo`            | The curve is not in the supported list     |\n| `Either privateKey or publicKey is required` | No key material was passed                 |\n| `Only supports raw keys in Buffer`           | Key material is not a `Buffer`             |\n| `Invalid DER encoding of ECPrivateKey`       | Malformed SEC1 private key DER             |\n| `Invalid DER encoding of PrivateKeyInfo`     | Malformed PKCS#8 private key DER           |\n| `Not an EC private key (algorithm OID: …)`   | PKCS#8 holding an RSA, OKP or other key    |\n| `Encrypted PEM requires a passphrase`        | Encrypted key without `{ passphrase }`     |\n| `Public key is not a point on …`             | The point is not on the named curve        |\n| `Private key is out of range for curve …`    | Zero, or not below the curve order         |\n| `Public key does not match the private key…` | The two keys come from different pairs     |\n| `Cannot decrypt the private key: …`          | Wrong passphrase, or an unsupported cipher |\n| `Unsupported PEM label \"…\"`                  | A PEM block this library does not handle   |\n\n## Supported curves\n\n`CURVE_NAMES` lists all 79 names, `CURVE_OIDS` maps each one to its OID, `CURVE_KEY_BYTES` gives\nits coordinate size in bytes and `CURVE_PRIVATE_KEY_BYTES` its private key size, which differs on 17\ncurves (secp224k1 keys are 29 bytes, sect233k1 keys 29, for example).\n\n| Family               | Example                               |\n| -------------------- | ------------------------------------- |\n| ANSI X9.62 prime     | `prime256v1`                          |\n| SEC 2 prime          | `secp256k1`, `secp384r1`, `secp521r1` |\n| SEC 2 binary         | `sect233k1`, `sect571r1`              |\n| Brainpool (RFC 5639) | `brainpoolP256r1`                     |\n| ANSI X9.62 binary    | `c2pnb163v1`, `c2tnb431r1`            |\n| WAP WSG (RFC 2409)   | `wap-wsg-idm-ecid-wtls12`             |\n\nOKP curves are not EC curves and are not in that list: `OKP_CURVES` covers `Ed25519` and `Ed448`,\nwhich are available for JWK only.\n\nNot every curve is usable for signing: which curves OpenSSL accepts for ECDSA depends on the Node\nand OpenSSL build you run.\n\n## Caveats\n\n- **Do not reuse one key pair for both ECDH and ECDSA** unless you are certain the risk does not\n  apply to you. The original motivation for this library was convenience, not key separation.\n- **PEM is EC only.** `Ed25519` and `Ed448` keys are supported as JWK, but a PKCS#8 PEM for them is\n  rejected (`Not an EC private key`), because their PEM containers hold no EC parameters.\n- **Encrypted SEC1 output is legacy.** `{ passphrase }` alone writes PKCS#8 (PBES2, PBKDF2 with\n  2048 iterations and hmacWithSHA256); `{ type: 'sec1', passphrase }` writes the older\n  `Proc-Type: 4,ENCRYPTED` container, which derives its key with `EVP_BytesToKey`. Prefer PKCS#8.\n  `RSA PRIVATE KEY` blocks and certificates are rejected by name.\n\n- **Checks need the curve in your OpenSSL.** Points, private key ranges and key pairs are checked by\n  the OpenSSL that Node runs on. On a curve that build lacks (some drop the binary curves), keys are\n  still encoded and parsed, but only their sizes are checked and compressed points cannot be\n  expanded.\n- **Modern Node can often skip this library.** `crypto.createPrivateKey({ key: jwk, format: 'jwk' })`\n  builds a `KeyObject` from a JWK directly (Node 15.12+). This library remains useful when you have\n  raw keys and need PEM, or need to parse PEM back into raw keys.\n\n## Security\n\nSee [SECURITY.md](./SECURITY.md) for supported versions and how to report a vulnerability.\n\n## Contributing\n\nIssues and pull requests are welcome. See [CONTRIBUTING.md](./CONTRIBUTING.md) for the local\nworkflow, and [CHANGELOG.md](./CHANGELOG.md) for release notes.\n\n```bash\nnpm install\nnpm run check   # typecheck, lint, tests, build\n```\n\n## License\n\nISC © 2018-2026 tibetty\n","publish_time":1545031573601,"_cnpm_publish_time":1545031573601,"dist-tags":{"latest":"2.0.0"}}