@decryption/curves 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +75 -0
  3. package/abstract/bls.d.ts +410 -0
  4. package/abstract/bls.js +433 -0
  5. package/abstract/curve.d.ts +441 -0
  6. package/abstract/curve.js +622 -0
  7. package/abstract/edwards.d.ts +319 -0
  8. package/abstract/edwards.js +697 -0
  9. package/abstract/fft.d.ts +438 -0
  10. package/abstract/fft.js +580 -0
  11. package/abstract/frost.d.ts +292 -0
  12. package/abstract/frost.js +705 -0
  13. package/abstract/hash-to-curve.d.ts +238 -0
  14. package/abstract/hash-to-curve.js +353 -0
  15. package/abstract/modular.d.ts +550 -0
  16. package/abstract/modular.js +872 -0
  17. package/abstract/montgomery.d.ts +95 -0
  18. package/abstract/montgomery.js +180 -0
  19. package/abstract/oprf.d.ts +354 -0
  20. package/abstract/oprf.js +358 -0
  21. package/abstract/poseidon.d.ts +198 -0
  22. package/abstract/poseidon.js +471 -0
  23. package/abstract/tower.d.ts +213 -0
  24. package/abstract/tower.js +963 -0
  25. package/abstract/weierstrass.d.ts +587 -0
  26. package/abstract/weierstrass.js +1421 -0
  27. package/bls12-381.d.ts +23 -0
  28. package/bls12-381.js +680 -0
  29. package/bn254.d.ts +74 -0
  30. package/bn254.js +248 -0
  31. package/ed25519.d.ts +211 -0
  32. package/ed25519.js +626 -0
  33. package/ed448.d.ts +184 -0
  34. package/ed448.js +596 -0
  35. package/esm/abstract/bls.js +429 -0
  36. package/esm/abstract/curve.js +610 -0
  37. package/esm/abstract/edwards.js +691 -0
  38. package/esm/abstract/fft.js +567 -0
  39. package/esm/abstract/frost.js +702 -0
  40. package/esm/abstract/hash-to-curve.js +345 -0
  41. package/esm/abstract/modular.js +849 -0
  42. package/esm/abstract/montgomery.js +177 -0
  43. package/esm/abstract/oprf.js +355 -0
  44. package/esm/abstract/poseidon.js +462 -0
  45. package/esm/abstract/tower.js +925 -0
  46. package/esm/abstract/weierstrass.js +1411 -0
  47. package/esm/bls12-381.js +677 -0
  48. package/esm/bn254.js +244 -0
  49. package/esm/ed25519.js +622 -0
  50. package/esm/ed448.js +593 -0
  51. package/esm/index.js +38 -0
  52. package/esm/misc.js +211 -0
  53. package/esm/nist.js +266 -0
  54. package/esm/secp256k1.js +465 -0
  55. package/esm/utils.js +597 -0
  56. package/esm/webcrypto.js +362 -0
  57. package/index.d.ts +0 -0
  58. package/index.js +38 -0
  59. package/misc.d.ts +113 -0
  60. package/misc.js +216 -0
  61. package/nist.d.ts +136 -0
  62. package/nist.js +269 -0
  63. package/package.json +46 -0
  64. package/secp256k1.d.ts +152 -0
  65. package/secp256k1.js +468 -0
  66. package/utils.d.ts +535 -0
  67. package/utils.js +626 -0
  68. package/webcrypto.d.ts +240 -0
  69. package/webcrypto.js +365 -0
package/webcrypto.d.ts ADDED
@@ -0,0 +1,240 @@
1
+ /**
2
+ * Friendly wrapper over elliptic curves from built-in WebCrypto. Experimental: API may change.
3
+
4
+ # WebCrypto issues
5
+
6
+ ## No way to get public keys
7
+
8
+ - Export of raw secret key is prohibited by spec:
9
+ - https://w3c.github.io/webcrypto/#ecdsa-operations-export-key
10
+ -> "If format is "raw":" -> "If the [[type]] internal slot of key is not "public",
11
+ then throw an InvalidAccessError."
12
+ - Import of raw secret keys is prohibited by spec:
13
+ - https://w3c.github.io/webcrypto/#ecdsa-operations-import-key
14
+ -> "If format is "raw":" -> "If usages contains a value which is not "verify"
15
+ then throw a SyntaxError."
16
+ - SPKI (Simple public-key infrastructure) is public-key-only
17
+ - PKCS8 is secret-key-only
18
+ - No way to get public key from secret key, but we convert to JWK and then
19
+ create it manually, since a JWK secret key includes both private and public
20
+ parts.
21
+ - Noble supports generating keys for both sign, verify & getSharedSecret,
22
+ but JWK key includes usage, which forces us to patch it (non-JWK is ok)
23
+ - We have import/export for 'raw', but it doesn't work in Firefox / Safari
24
+
25
+ ## Point encoding
26
+
27
+ - Raw export of public points returns uncompressed points,
28
+ but this is implementation specific and not much we can do there.
29
+ - `getSharedSecret` differs for p256, p384, p521:
30
+ Noble returns 33-byte output (y-parity + x coordinate),
31
+ while in WebCrypto returns 32-byte output (x coordinate).
32
+ This is intentional: noble keeps the full encoded shared point, and x-only
33
+ callers can slice it down themselves.
34
+ - `getSharedSecret` identical for X25519, X448
35
+
36
+ ## Availability
37
+
38
+ Node.js additionally supports ed448.
39
+ There seems no reasonable way to check for availability, other than actually calling methods.
40
+
41
+ * @module
42
+ */
43
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
44
+ import type { TArg, TRet } from './utils';
45
+ /** Raw type */
46
+ declare const TYPE_RAW = "raw";
47
+ declare const TYPE_JWK = "jwk";
48
+ declare const TYPE_SPKI = "spki";
49
+ declare const TYPE_PKCS = "pkcs8";
50
+ /** Key serialization formats supported by the WebCrypto wrappers. */
51
+ export type WebCryptoFormat = typeof TYPE_RAW | typeof TYPE_JWK | typeof TYPE_SPKI | typeof TYPE_PKCS;
52
+ /** WebCrypto keys can be in raw, jwk, pkcs8/spki formats. Raw is internal and fragile. */
53
+ export type WebCryptoOpts = {
54
+ /** Preferred secret-key serialization format. */
55
+ formatSec?: WebCryptoFormat;
56
+ /** Preferred public-key serialization format. */
57
+ formatPub?: WebCryptoFormat;
58
+ };
59
+ declare function hexToBytesLocal(hex: string): TRet<Uint8Array>;
60
+ export declare const __TEST: {
61
+ hexToBytesLocal: typeof hexToBytesLocal;
62
+ };
63
+ type JsonWebKey = {
64
+ crv?: string;
65
+ d?: string;
66
+ kty?: string;
67
+ x?: string;
68
+ y?: string;
69
+ [key: string]: unknown;
70
+ };
71
+ type Key = JsonWebKey | Uint8Array;
72
+ type WebCryptoBaseCurve = {
73
+ name: string;
74
+ isSupported(): Promise<boolean>;
75
+ keygen(): TRet<Promise<{
76
+ secretKey: Uint8Array;
77
+ publicKey: Uint8Array;
78
+ }>>;
79
+ getPublicKey(secretKey: TArg<Key>, opts?: TArg<WebCryptoOpts>): TRet<Promise<Key>>;
80
+ utils: {
81
+ randomSecretKey: (format?: WebCryptoFormat) => TRet<Promise<Key>>;
82
+ convertSecretKey: (key: TArg<Key>, inFormat?: WebCryptoFormat, outFormat?: WebCryptoFormat) => TRet<Promise<Key>>;
83
+ convertPublicKey: (key: TArg<Key>, inFormat?: WebCryptoFormat, outFormat?: WebCryptoFormat) => TRet<Promise<Key>>;
84
+ };
85
+ };
86
+ /** WebCrypto signing interface shared by ECDSA and EdDSA helpers. */
87
+ export type WebCryptoSigner = {
88
+ /**
89
+ * Sign one message with a WebCrypto-backed private key.
90
+ * @param message - Message bytes to sign.
91
+ * @param secretKey - Secret key in one supported format.
92
+ * @param opts - Optional key-format overrides. See {@link WebCryptoOpts}.
93
+ * @returns Signature bytes.
94
+ */
95
+ sign(message: TArg<Uint8Array>, secretKey: TArg<Key>, opts?: TArg<WebCryptoOpts>): TRet<Promise<Uint8Array>>;
96
+ /**
97
+ * Verify one signature with a WebCrypto-backed public key.
98
+ * @param signature - Signature bytes.
99
+ * @param message - Signed message bytes.
100
+ * @param publicKey - Public key in one supported format.
101
+ * @param opts - Optional key-format overrides. See {@link WebCryptoOpts}.
102
+ * @returns `true` when the signature is valid.
103
+ */
104
+ verify(signature: TArg<Uint8Array>, message: TArg<Uint8Array>, publicKey: TArg<Key>, opts?: TArg<WebCryptoOpts>): Promise<boolean>;
105
+ };
106
+ /** WebCrypto ECDH interface for shared-secret derivation. */
107
+ export type WebCryptoECDH = {
108
+ /**
109
+ * Derive one shared secret from a local secret key and peer public key.
110
+ * Short-Weierstrass wrappers return the raw x-coordinate here, not noble's parity-prefixed
111
+ * shared-point encoding. Runtime also accepts alternate key formats through `opts`, even though
112
+ * this public type is still narrowed to byte arrays.
113
+ * @param secA - Local secret key in one supported format.
114
+ * @param pubB - Peer public key in one supported format.
115
+ * @param opts - Optional key-format overrides. See {@link WebCryptoOpts}.
116
+ * @returns Shared secret bytes.
117
+ */
118
+ getSharedSecret(secA: TArg<Uint8Array>, pubB: TArg<Uint8Array>, opts?: TArg<WebCryptoOpts>): TRet<Promise<Uint8Array>>;
119
+ };
120
+ /** WebCrypto ECDSA interface with keygen, signing, and ECDH helpers. */
121
+ export type WebCryptoECDSA = WebCryptoBaseCurve & WebCryptoSigner & WebCryptoECDH;
122
+ /** WebCrypto EdDSA interface with keygen and signing helpers. */
123
+ export type WebCryptoEdDSA = WebCryptoBaseCurve & WebCryptoSigner;
124
+ /** WebCrypto Montgomery interface with keygen and ECDH helpers. */
125
+ export type WebCryptoMontgomery = WebCryptoBaseCurve & WebCryptoECDH;
126
+ /**
127
+ * Friendly wrapper over built-in WebCrypto NIST P-256 (secp256r1).
128
+ * Inherits the generic WebCrypto ECDSA caveats: `isSupported()` only probes the sign-side API, and
129
+ * the conversion/signing helpers keep the shared `createKeyUtils(...)` / `createSigner(...)` quirks,
130
+ * including raw WebCrypto ECDSA signatures without low-S normalization.
131
+ * @example
132
+ * Check support, then sign and verify once with WebCrypto P-256.
133
+ *
134
+ * ```ts
135
+ * if (await p256.isSupported()) {
136
+ * const { secretKey, publicKey } = await p256.keygen();
137
+ * const msg = new TextEncoder().encode('hello noble');
138
+ * const sig = await p256.sign(msg, secretKey);
139
+ * const isValid = await p256.verify(sig, msg, publicKey);
140
+ * }
141
+ * ```
142
+ */
143
+ export declare const p256: TRet<WebCryptoECDSA>;
144
+ /**
145
+ * Friendly wrapper over built-in WebCrypto NIST P-384 (secp384r1).
146
+ * Inherits the generic WebCrypto ECDSA caveats around support probing and key/signing conversion.
147
+ * @example
148
+ * Check support, then sign and verify once with WebCrypto P-384.
149
+ *
150
+ * ```ts
151
+ * if (await p384.isSupported()) {
152
+ * const { secretKey, publicKey } = await p384.keygen();
153
+ * const msg = new TextEncoder().encode('hello noble');
154
+ * const sig = await p384.sign(msg, secretKey);
155
+ * const isValid = await p384.verify(sig, msg, publicKey);
156
+ * }
157
+ * ```
158
+ */
159
+ export declare const p384: TRet<WebCryptoECDSA>;
160
+ /**
161
+ * Friendly wrapper over built-in WebCrypto NIST P-521 (secp521r1).
162
+ * Inherits the generic WebCrypto ECDSA caveats around support probing and key/signing conversion.
163
+ * @example
164
+ * Check support, then sign and verify once with WebCrypto P-521.
165
+ *
166
+ * ```ts
167
+ * if (await p521.isSupported()) {
168
+ * const { secretKey, publicKey } = await p521.keygen();
169
+ * const msg = new TextEncoder().encode('hello noble');
170
+ * const sig = await p521.sign(msg, secretKey);
171
+ * const isValid = await p521.verify(sig, msg, publicKey);
172
+ * }
173
+ * ```
174
+ */
175
+ export declare const p521: TRet<WebCryptoECDSA>;
176
+ /**
177
+ * Friendly wrapper over built-in WebCrypto ed25519.
178
+ * Inherits the generic WebCrypto EdDSA caveats around JWK conversion metadata and extractability.
179
+ * @example
180
+ * Check support, then sign and verify once with WebCrypto Ed25519.
181
+ *
182
+ * ```ts
183
+ * if (await ed25519.isSupported()) {
184
+ * const { secretKey, publicKey } = await ed25519.keygen();
185
+ * const msg = new TextEncoder().encode('hello noble');
186
+ * const sig = await ed25519.sign(msg, secretKey);
187
+ * const isValid = await ed25519.verify(sig, msg, publicKey);
188
+ * }
189
+ * ```
190
+ */
191
+ export declare const ed25519: TRet<WebCryptoEdDSA>;
192
+ /**
193
+ * Friendly wrapper over built-in WebCrypto ed448.
194
+ * Inherits the generic WebCrypto EdDSA caveats around JWK conversion metadata and extractability.
195
+ * @example
196
+ * Check support, then sign and verify once with WebCrypto Ed448.
197
+ *
198
+ * ```ts
199
+ * if (await ed448.isSupported()) {
200
+ * const { secretKey, publicKey } = await ed448.keygen();
201
+ * const msg = new TextEncoder().encode('hello noble');
202
+ * const sig = await ed448.sign(msg, secretKey);
203
+ * const isValid = await ed448.verify(sig, msg, publicKey);
204
+ * }
205
+ * ```
206
+ */
207
+ export declare const ed448: TRet<WebCryptoEdDSA>;
208
+ /**
209
+ * Friendly wrapper over built-in WebCrypto x25519 (ECDH over Curve25519).
210
+ * Inherits the generic WebCrypto Montgomery caveat that runtime accepts more key formats than the
211
+ * narrow public `Uint8Array` argument types suggest.
212
+ * @example
213
+ * Check support, then derive one shared secret with WebCrypto X25519.
214
+ *
215
+ * ```ts
216
+ * if (await x25519.isSupported()) {
217
+ * const alice = await x25519.keygen();
218
+ * const bob = await x25519.keygen();
219
+ * const shared = await x25519.getSharedSecret(alice.secretKey, bob.publicKey);
220
+ * }
221
+ * ```
222
+ */
223
+ export declare const x25519: TRet<WebCryptoMontgomery>;
224
+ /**
225
+ * Friendly wrapper over built-in WebCrypto x448 (ECDH over Curve448).
226
+ * Inherits the generic WebCrypto Montgomery caveat that runtime accepts more key formats than the
227
+ * narrow public `Uint8Array` argument types suggest.
228
+ * @example
229
+ * Check support, then derive one shared secret with WebCrypto X448.
230
+ *
231
+ * ```ts
232
+ * if (await x448.isSupported()) {
233
+ * const alice = await x448.keygen();
234
+ * const bob = await x448.keygen();
235
+ * const shared = await x448.getSharedSecret(alice.secretKey, bob.publicKey);
236
+ * }
237
+ * ```
238
+ */
239
+ export declare const x448: TRet<WebCryptoMontgomery>;
240
+ export {};
package/webcrypto.js ADDED
@@ -0,0 +1,365 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.x448 = exports.x25519 = exports.ed448 = exports.ed25519 = exports.p521 = exports.p384 = exports.p256 = exports.__TEST = void 0;
4
+ /** Raw type */
5
+ const TYPE_RAW = 'raw';
6
+ const TYPE_JWK = 'jwk';
7
+ const TYPE_SPKI = 'spki';
8
+ const TYPE_PKCS = 'pkcs8';
9
+ // default formats
10
+ const dfsec = TYPE_PKCS;
11
+ const dfpub = TYPE_SPKI;
12
+ function getSubtle() {
13
+ const s = globalThis?.crypto?.subtle;
14
+ if (typeof s === 'object' && s != null)
15
+ return s;
16
+ throw new Error('crypto.subtle must be defined');
17
+ }
18
+ function createKeygenA(randomSecretKey, getPublicKey) {
19
+ // Runtime accepts an accidental `keygen(seed)` argument for parity with other wrappers, but the
20
+ // seed is intentionally ignored because WebCrypto keygen here always goes through fresh keygen.
21
+ return async function keygenA(_seed) {
22
+ const secretKey = (await randomSecretKey());
23
+ return { secretKey, publicKey: (await getPublicKey(secretKey)) };
24
+ };
25
+ }
26
+ // Internal helper only: strict hex parser for the local hardcoded PKCS8 header constants.
27
+ function hexToBytesLocal(hex) {
28
+ const pairs = hex.match(/[0-9a-f]{2}/gi);
29
+ if (!pairs || pairs.length * 2 !== hex.length)
30
+ throw new Error('invalid hex');
31
+ return Uint8Array.from(pairs, (b) => Number.parseInt(b, 16));
32
+ }
33
+ exports.__TEST = Object.freeze({
34
+ hexToBytesLocal,
35
+ });
36
+ function assertType(type, key) {
37
+ // Callers are expected to pass a non-null key-like object; `null` / `undefined` still fail first
38
+ // via property access before reaching the explicit wrapper error.
39
+ if (key.type !== type)
40
+ throw new Error(`invalid key type, expected ${type}`);
41
+ }
42
+ function createKeyUtils(algo, derive, keyLen, pkcs8header) {
43
+ const secUsage = derive ? ['deriveBits'] : ['sign'];
44
+ const pubUsage = derive ? [] : ['verify'];
45
+ // Return Uint8Array instead of ArrayBuffer
46
+ const arrBufToU8 = (res, format) => (format === TYPE_JWK
47
+ ? res
48
+ : new Uint8Array(res));
49
+ const pub = {
50
+ async import(key, format) {
51
+ // For sign/verify wrappers we pass caller-provided JWK metadata through unchanged and let
52
+ // WebCrypto enforce mismatched `key_ops` / extractability instead of normalizing it here.
53
+ const keyi = await getSubtle().importKey(format, key, algo, true, pubUsage);
54
+ assertType('public', keyi);
55
+ return keyi;
56
+ },
57
+ async export(key, format) {
58
+ assertType('public', key);
59
+ const keyi = await getSubtle().exportKey(format, key);
60
+ return arrBufToU8(keyi, format);
61
+ },
62
+ async convert(key, inFormat, outFormat) {
63
+ return pub.export(await pub.import(key, inFormat), outFormat);
64
+ },
65
+ };
66
+ const priv = {
67
+ async import(key, format) {
68
+ const crypto = getSubtle();
69
+ let keyi;
70
+ if (format === TYPE_RAW) {
71
+ // Chrome, node, bun, deno: works
72
+ // Safari, Firefox: Data provided to an operation does not meet requirements
73
+ // This is the best one can do. JWK can't be used: it contains public key component inside.
74
+ const k = key;
75
+ const head = hexToBytesLocal(pkcs8header);
76
+ const all = new Uint8Array(head.length + k.length);
77
+ all.set(head, 0);
78
+ all.set(k, head.length);
79
+ keyi = await crypto.importKey(TYPE_PKCS, all, algo, true, secUsage);
80
+ }
81
+ else {
82
+ // Sign/verify wrappers keep caller JWK metadata as-is and assume the supplied `key_ops`
83
+ // already match the requested operation. ECDH is different: noble treats the same key
84
+ // material as usable for both sign and derive, so JWK imported through the derive path
85
+ // must rewrite `key_ops` or WebCrypto refuses otherwise-correct keys exported by keygen.
86
+ if (derive && format === TYPE_JWK)
87
+ key = { ...key, key_ops: secUsage };
88
+ keyi = await crypto.importKey(format, key, algo, true, secUsage);
89
+ }
90
+ assertType('private', keyi);
91
+ return keyi;
92
+ },
93
+ async export(key, format) {
94
+ const crypto = getSubtle();
95
+ assertType('private', key);
96
+ if (format === TYPE_RAW) {
97
+ // scure-base base64urlnopad could have been used, but we can't add more deps.
98
+ // pkcs8 would be even more fragile
99
+ const jwk = await crypto.exportKey(TYPE_JWK, key);
100
+ const base64 = jwk.d.replace(/-/g, '+').replace(/_/g, '/'); // base64url
101
+ const pad = base64.length % 4 ? '='.repeat(4 - (base64.length % 4)) : ''; // add padding
102
+ const binary = atob(base64 + pad);
103
+ // This is not ASCII, and not text: this is only semi-safe with atob output
104
+ const raw = Uint8Array.from(binary, (c) => c.charCodeAt(0));
105
+ // Pad key to key len because Bun strips leading zero for P-521 only
106
+ const res = new Uint8Array(keyLen);
107
+ res.set(raw, keyLen - raw.length);
108
+ return res;
109
+ }
110
+ const keyi = await crypto.exportKey(format, key);
111
+ return arrBufToU8(keyi, format);
112
+ },
113
+ async convert(key, inFormat, outFormat) {
114
+ return priv.export(await priv.import(key, inFormat), outFormat);
115
+ },
116
+ };
117
+ async function getPublicKey(secretKey, opts = {}) {
118
+ const fsec = opts.formatSec ?? dfsec;
119
+ const fpub = opts.formatPub ?? dfpub;
120
+ // Export to jwk, remove private scalar and then convert to format
121
+ const jwk = (fsec === TYPE_JWK ? { ...secretKey } : await priv.convert(secretKey, fsec, TYPE_JWK));
122
+ delete jwk.d;
123
+ jwk.key_ops = pubUsage;
124
+ if (fpub === TYPE_JWK)
125
+ return jwk;
126
+ return pub.convert(jwk, TYPE_JWK, fpub);
127
+ }
128
+ async function randomSecretKey(format = dfsec) {
129
+ const keyPair = await getSubtle().generateKey(algo, true, secUsage);
130
+ return priv.export(keyPair.privateKey, format);
131
+ }
132
+ // Key generation could be slow, so we cache result once.
133
+ let supported;
134
+ return {
135
+ pub: pub,
136
+ priv: priv,
137
+ async isSupported() {
138
+ if (supported !== undefined)
139
+ return supported;
140
+ try {
141
+ const crypto = getSubtle();
142
+ const key = await crypto.generateKey(algo, true, secUsage);
143
+ // Deno is broken and generates key for unsupported curves, but then fails on export
144
+ await priv.export(key.privateKey, TYPE_JWK);
145
+ // Bun fails on derive for x25519, but not x448
146
+ if (derive) {
147
+ await crypto.deriveBits({ name: typeof algo === 'string' ? algo : algo.name, public: key.publicKey }, key.privateKey, 8);
148
+ }
149
+ return (supported = true);
150
+ }
151
+ catch (e) {
152
+ return (supported = false);
153
+ }
154
+ },
155
+ getPublicKey,
156
+ keygen: createKeygenA(randomSecretKey, getPublicKey),
157
+ utils: Object.freeze({
158
+ randomSecretKey,
159
+ // Runtime expects both formats explicitly here; omitted formats just flow into
160
+ // `subtle.importKey(...)`, and JWK conversion also assumes extractable keys (`ext !== false`).
161
+ convertPublicKey: pub.convert,
162
+ // Runtime expects both formats explicitly here; omitted formats just flow into
163
+ // `subtle.importKey(...)`, and JWK conversion also assumes extractable keys (`ext !== false`).
164
+ convertSecretKey: priv.convert,
165
+ }),
166
+ };
167
+ }
168
+ function createSigner(keys, algo) {
169
+ return {
170
+ // Historical param name: wrappers pass message bytes here, while WebCrypto performs the
171
+ // algorithm-specific hashing itself for ECDSA. We also return provider signatures verbatim:
172
+ // this wrapper is intentionally "raw WebCrypto", so it does not parse scalars or normalize
173
+ // high-S ECDSA outputs into software noble's low-S convention.
174
+ async sign(msgHash, secretKey, opts = {}) {
175
+ const key = await keys.priv.import(secretKey, opts.formatSec ?? dfsec);
176
+ const sig = await getSubtle().sign(algo, key, msgHash);
177
+ return new Uint8Array(sig);
178
+ },
179
+ async verify(signature, msgHash, publicKey, opts = {}) {
180
+ const key = await keys.pub.import(publicKey, opts.formatPub ?? dfpub);
181
+ return await getSubtle().verify(algo, key, signature, msgHash);
182
+ },
183
+ };
184
+ }
185
+ function createECDH(keys, algo, keyLen) {
186
+ return {
187
+ // Runtime accepts the alternate key formats supported by `keys.import(...)`; the public type is
188
+ // still narrower than that accepted surface.
189
+ async getSharedSecret(secretKeyA, publicKeyB, opts = {}) {
190
+ // if (_isCompressed !== true) throw new Error('WebCrypto only supports compressed keys');
191
+ const secKey = await keys.priv.import(secretKeyA, opts.formatSec === undefined ? dfsec : opts.formatSec);
192
+ const pubKey = await keys.pub.import(publicKeyB, opts.formatPub === undefined ? dfpub : opts.formatPub);
193
+ const shared = await getSubtle().deriveBits({ name: typeof algo === 'string' ? algo : algo.name, public: pubKey }, secKey, 8 * keyLen);
194
+ return new Uint8Array(shared);
195
+ },
196
+ };
197
+ }
198
+ function wrapECDSA(curve, hash, keyLen, pkcs8header) {
199
+ const ECDH_ALGO = { name: 'ECDH', namedCurve: curve };
200
+ const keys = createKeyUtils({ name: 'ECDSA', namedCurve: curve }, false, keyLen, pkcs8header);
201
+ const keysEcdh = createKeyUtils(ECDH_ALGO, true, keyLen, pkcs8header);
202
+ return Object.freeze({
203
+ name: curve,
204
+ // Support probing comes from the sign-side wrapper only; ECDH availability is not checked
205
+ // independently here even though the public wrapper also exposes `getSharedSecret(...)`.
206
+ isSupported: keys.isSupported,
207
+ getPublicKey: keys.getPublicKey,
208
+ keygen: createKeygenA(keys.utils.randomSecretKey, keys.getPublicKey),
209
+ ...createSigner(keys, { name: 'ECDSA', hash: { name: hash } }),
210
+ ...createECDH(keysEcdh, ECDH_ALGO, keyLen),
211
+ utils: Object.freeze({
212
+ ...keys.utils,
213
+ async convertSecretKey(key, inFormat, outFormat) {
214
+ const jwk = inFormat === TYPE_JWK ? key : undefined;
215
+ // `wrapECDSA(...)` exposes the same key material for both sign and derive, so an ECDH-flavored
216
+ // JWK secret key from `getSharedSecret(...)` should still round-trip through `utils`.
217
+ if (Array.isArray(jwk?.key_ops) &&
218
+ jwk.key_ops.length === 1 &&
219
+ jwk.key_ops[0] === 'deriveBits')
220
+ return keysEcdh.utils.convertSecretKey(key, inFormat, outFormat);
221
+ return keys.utils.convertSecretKey(key, inFormat, outFormat);
222
+ },
223
+ }),
224
+ });
225
+ }
226
+ function wrapEdDSA(curve, keyLen, pkcs8header) {
227
+ const keys = createKeyUtils(curve, false, keyLen, pkcs8header);
228
+ return Object.freeze({
229
+ name: curve,
230
+ isSupported: keys.isSupported,
231
+ // This wrapper intentionally re-exports the generic WebCrypto key-conversion/signing behavior
232
+ // without adding extra JWK-metadata or extractability guardrails of its own.
233
+ getPublicKey: keys.getPublicKey,
234
+ keygen: createKeygenA(keys.utils.randomSecretKey, keys.getPublicKey),
235
+ ...createSigner(keys, { name: curve }),
236
+ utils: keys.utils,
237
+ });
238
+ }
239
+ function wrapMontgomery(curve, keyLen, pkcs8header) {
240
+ const keys = createKeyUtils(curve, true, keyLen, pkcs8header);
241
+ return Object.freeze({
242
+ name: curve,
243
+ isSupported: keys.isSupported,
244
+ // This wrapper intentionally re-exports the generic ECDH key-format behavior without widening
245
+ // the narrow public `Uint8Array` key types.
246
+ getPublicKey: keys.getPublicKey,
247
+ keygen: createKeygenA(keys.utils.randomSecretKey, keys.getPublicKey),
248
+ ...createECDH(keys, curve, keyLen),
249
+ utils: keys.utils,
250
+ });
251
+ }
252
+ /**
253
+ * Friendly wrapper over built-in WebCrypto NIST P-256 (secp256r1).
254
+ * Inherits the generic WebCrypto ECDSA caveats: `isSupported()` only probes the sign-side API, and
255
+ * the conversion/signing helpers keep the shared `createKeyUtils(...)` / `createSigner(...)` quirks,
256
+ * including raw WebCrypto ECDSA signatures without low-S normalization.
257
+ * @example
258
+ * Check support, then sign and verify once with WebCrypto P-256.
259
+ *
260
+ * ```ts
261
+ * if (await p256.isSupported()) {
262
+ * const { secretKey, publicKey } = await p256.keygen();
263
+ * const msg = new TextEncoder().encode('hello noble');
264
+ * const sig = await p256.sign(msg, secretKey);
265
+ * const isValid = await p256.verify(sig, msg, publicKey);
266
+ * }
267
+ * ```
268
+ */
269
+ exports.p256 = wrapECDSA('P-256', 'SHA-256', 32, '3041020100301306072a8648ce3d020106082a8648ce3d030107042730250201010420');
270
+ /**
271
+ * Friendly wrapper over built-in WebCrypto NIST P-384 (secp384r1).
272
+ * Inherits the generic WebCrypto ECDSA caveats around support probing and key/signing conversion.
273
+ * @example
274
+ * Check support, then sign and verify once with WebCrypto P-384.
275
+ *
276
+ * ```ts
277
+ * if (await p384.isSupported()) {
278
+ * const { secretKey, publicKey } = await p384.keygen();
279
+ * const msg = new TextEncoder().encode('hello noble');
280
+ * const sig = await p384.sign(msg, secretKey);
281
+ * const isValid = await p384.verify(sig, msg, publicKey);
282
+ * }
283
+ * ```
284
+ */
285
+ exports.p384 = wrapECDSA('P-384', 'SHA-384', 48, '304e020100301006072a8648ce3d020106052b81040022043730350201010430');
286
+ /**
287
+ * Friendly wrapper over built-in WebCrypto NIST P-521 (secp521r1).
288
+ * Inherits the generic WebCrypto ECDSA caveats around support probing and key/signing conversion.
289
+ * @example
290
+ * Check support, then sign and verify once with WebCrypto P-521.
291
+ *
292
+ * ```ts
293
+ * if (await p521.isSupported()) {
294
+ * const { secretKey, publicKey } = await p521.keygen();
295
+ * const msg = new TextEncoder().encode('hello noble');
296
+ * const sig = await p521.sign(msg, secretKey);
297
+ * const isValid = await p521.verify(sig, msg, publicKey);
298
+ * }
299
+ * ```
300
+ */
301
+ exports.p521 = wrapECDSA('P-521', 'SHA-512', 66, '3060020100301006072a8648ce3d020106052b81040023044930470201010442');
302
+ /**
303
+ * Friendly wrapper over built-in WebCrypto ed25519.
304
+ * Inherits the generic WebCrypto EdDSA caveats around JWK conversion metadata and extractability.
305
+ * @example
306
+ * Check support, then sign and verify once with WebCrypto Ed25519.
307
+ *
308
+ * ```ts
309
+ * if (await ed25519.isSupported()) {
310
+ * const { secretKey, publicKey } = await ed25519.keygen();
311
+ * const msg = new TextEncoder().encode('hello noble');
312
+ * const sig = await ed25519.sign(msg, secretKey);
313
+ * const isValid = await ed25519.verify(sig, msg, publicKey);
314
+ * }
315
+ * ```
316
+ */
317
+ exports.ed25519 = wrapEdDSA('Ed25519', 32, '302e020100300506032b657004220420');
318
+ /**
319
+ * Friendly wrapper over built-in WebCrypto ed448.
320
+ * Inherits the generic WebCrypto EdDSA caveats around JWK conversion metadata and extractability.
321
+ * @example
322
+ * Check support, then sign and verify once with WebCrypto Ed448.
323
+ *
324
+ * ```ts
325
+ * if (await ed448.isSupported()) {
326
+ * const { secretKey, publicKey } = await ed448.keygen();
327
+ * const msg = new TextEncoder().encode('hello noble');
328
+ * const sig = await ed448.sign(msg, secretKey);
329
+ * const isValid = await ed448.verify(sig, msg, publicKey);
330
+ * }
331
+ * ```
332
+ */
333
+ exports.ed448 = wrapEdDSA('Ed448', 57, '3047020100300506032b6571043b0439');
334
+ /**
335
+ * Friendly wrapper over built-in WebCrypto x25519 (ECDH over Curve25519).
336
+ * Inherits the generic WebCrypto Montgomery caveat that runtime accepts more key formats than the
337
+ * narrow public `Uint8Array` argument types suggest.
338
+ * @example
339
+ * Check support, then derive one shared secret with WebCrypto X25519.
340
+ *
341
+ * ```ts
342
+ * if (await x25519.isSupported()) {
343
+ * const alice = await x25519.keygen();
344
+ * const bob = await x25519.keygen();
345
+ * const shared = await x25519.getSharedSecret(alice.secretKey, bob.publicKey);
346
+ * }
347
+ * ```
348
+ */
349
+ exports.x25519 = wrapMontgomery('X25519', 32, '302e020100300506032b656e04220420');
350
+ /**
351
+ * Friendly wrapper over built-in WebCrypto x448 (ECDH over Curve448).
352
+ * Inherits the generic WebCrypto Montgomery caveat that runtime accepts more key formats than the
353
+ * narrow public `Uint8Array` argument types suggest.
354
+ * @example
355
+ * Check support, then derive one shared secret with WebCrypto X448.
356
+ *
357
+ * ```ts
358
+ * if (await x448.isSupported()) {
359
+ * const alice = await x448.keygen();
360
+ * const bob = await x448.keygen();
361
+ * const shared = await x448.getSharedSecret(alice.secretKey, bob.publicKey);
362
+ * }
363
+ * ```
364
+ */
365
+ exports.x448 = wrapMontgomery('X448', 56, '3046020100300506032b656f043a0438');