{"name":"eckey-utils","version":"0.6.0","keywords":["ec","key","conversion","raw","PEM","ECDH","ECDSA","sign","verify"],"author":{"name":"tibetty"},"license":"ISC","_id":"eckey-utils@0.6.0","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":"1967996421c9c5b457f959bdbb6eb473b3a71411","tarball":"http://registry-npm.ywwl.com/eckey-utils/download/eckey-utils-0.6.0.tgz","fileCount":4,"integrity":"sha512-yeD7bU2q+GCZLZfAp+klwwGnVQQ1qURfEKpNsF9OJuq9E/ne6p3qBQ013VKM3UgtYbt7IoVyI4Sw5mbK1bgPfw==","signatures":[{"sig":"MEYCIQCxNM1LD45KPaj2tQ81Lq6k1WyI8AvzwUn4hMRgkJhJlAIhAO4Jgmg5Dc3/wIil+lR766Lp+XGJTRmdYKhZG5x23dDg","keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA"}],"unpackedSize":22691,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJcBmFVCRA9TVsSAnZWagAAUgMP/0czSgsP+qWrrhcTNpTc\nE18jax4tdJwi660u7fOxtPI0xD/iwNTII3xdTgVgWTVpPh92J9ioCOgGL3pw\nhku7G9k3zWaSFuqIaJHHDtRzkjLbaAuajAHqltZOCabAei7rRN24uDtxni4L\n0v85MHe6s5EE864OXa70lLzCoeFfPfPgfyxy+JLkhlph1Jy5QucMsD69MKAY\njvH8Y3xpAoJnJh0n33NMb+igY2odGwDPhONoRcnLb+CIwcfeUZiWtKwVyuFO\nb5jI50ERc+cxzGYDgqENiAVosyl1KskTw+DxP25bDlh0C5NOqDwuygMUEVCE\nYvJYG/xNyC0JSzM0njgqUMaQlmDULdDAGY5IVSqv/zLITILmaOQEmIt5QqkT\nf8Po3Wrxk70/ntwG9ix6Phnr8kEV4WlaXR1ISrGlF+klup/e3qE0nRLdAF++\nYsfWV380LCw6p0YwzyjViCVP2Xud8qfwU6CjzSoBmlVQKPTTgfa7ekmc9sIW\nZ94HmCEYZkCTw8wAWlM0cmDXQylUGCrj4MO24eul4tILyAp2mMrQnz/DnMgr\nNBWZvuvtNA48fsLjEKsFpzOaRekQNIAfe+NflefxYcjPJewBmzeS6FLTCde7\n0f2Ruwzo5EGcu66Be716JNbZL4ZEQigGMO4XrH//0q8gOvkC3xIoXSIqbrIT\ni1NL\r\n=z8qB\r\n-----END PGP SIGNATURE-----\r\n","size":5569,"noattachment":false,"key":"/eckey-utils/-/eckey-utils-0.6.0.tgz"},"main":"index.js","gitHead":"89d182d4a725662cf1fa760444602529dadd878c","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.4.1","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.3.0","_hasShrinkwrap":false,"_npmOperationalInternal":{"tmp":"tmp/eckey-utils_0.6.0_1543922004368_0.06775256442720101","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":1543922004520,"_cnpm_publish_time":1543922004520,"dist-tags":{"latest":"2.0.0"}}