@enbox/crypto 0.0.3 → 0.0.5

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 (116) hide show
  1. package/dist/browser.mjs +1 -1
  2. package/dist/browser.mjs.map +4 -4
  3. package/dist/esm/algorithms/aes-ctr.js +1 -1
  4. package/dist/esm/algorithms/aes-gcm.js +34 -1
  5. package/dist/esm/algorithms/aes-gcm.js.map +1 -1
  6. package/dist/esm/algorithms/aes-kw.js +154 -0
  7. package/dist/esm/algorithms/aes-kw.js.map +1 -0
  8. package/dist/esm/algorithms/ecdsa.js +110 -1
  9. package/dist/esm/algorithms/ecdsa.js.map +1 -1
  10. package/dist/esm/algorithms/eddsa.js +90 -1
  11. package/dist/esm/algorithms/eddsa.js.map +1 -1
  12. package/dist/esm/algorithms/hkdf.js +53 -0
  13. package/dist/esm/algorithms/hkdf.js.map +1 -0
  14. package/dist/esm/algorithms/pbkdf2.js +55 -0
  15. package/dist/esm/algorithms/pbkdf2.js.map +1 -0
  16. package/dist/esm/algorithms/sha-2.js +1 -1
  17. package/dist/esm/algorithms/x25519.js +125 -0
  18. package/dist/esm/algorithms/x25519.js.map +1 -0
  19. package/dist/esm/cose/cbor.js +35 -0
  20. package/dist/esm/cose/cbor.js.map +1 -0
  21. package/dist/esm/cose/cose-key.js +312 -0
  22. package/dist/esm/cose/cose-key.js.map +1 -0
  23. package/dist/esm/cose/cose-sign1.js +283 -0
  24. package/dist/esm/cose/cose-sign1.js.map +1 -0
  25. package/dist/esm/cose/eat.js +254 -0
  26. package/dist/esm/cose/eat.js.map +1 -0
  27. package/dist/esm/crypto-error.js +4 -0
  28. package/dist/esm/crypto-error.js.map +1 -1
  29. package/dist/esm/index.js +9 -0
  30. package/dist/esm/index.js.map +1 -1
  31. package/dist/esm/local-key-manager.js +6 -1
  32. package/dist/esm/local-key-manager.js.map +1 -1
  33. package/dist/esm/primitives/ecies-secp256k1.js +79 -0
  34. package/dist/esm/primitives/ecies-secp256k1.js.map +1 -0
  35. package/dist/esm/primitives/x25519.js +9 -16
  36. package/dist/esm/primitives/x25519.js.map +1 -1
  37. package/dist/esm/utils.js +30 -0
  38. package/dist/esm/utils.js.map +1 -1
  39. package/dist/types/algorithms/aes-ctr.d.ts +1 -1
  40. package/dist/types/algorithms/aes-gcm.d.ts +23 -3
  41. package/dist/types/algorithms/aes-gcm.d.ts.map +1 -1
  42. package/dist/types/algorithms/aes-kw.d.ts +129 -0
  43. package/dist/types/algorithms/aes-kw.d.ts.map +1 -0
  44. package/dist/types/algorithms/ecdsa.d.ts +48 -3
  45. package/dist/types/algorithms/ecdsa.d.ts.map +1 -1
  46. package/dist/types/algorithms/eddsa.d.ts +48 -3
  47. package/dist/types/algorithms/eddsa.d.ts.map +1 -1
  48. package/dist/types/algorithms/hkdf.d.ts +35 -0
  49. package/dist/types/algorithms/hkdf.d.ts.map +1 -0
  50. package/dist/types/algorithms/pbkdf2.d.ts +35 -0
  51. package/dist/types/algorithms/pbkdf2.d.ts.map +1 -0
  52. package/dist/types/algorithms/sha-2.d.ts +1 -1
  53. package/dist/types/algorithms/x25519.d.ts +76 -0
  54. package/dist/types/algorithms/x25519.d.ts.map +1 -0
  55. package/dist/types/cose/cbor.d.ts +30 -0
  56. package/dist/types/cose/cbor.d.ts.map +1 -0
  57. package/dist/types/cose/cose-key.d.ts +106 -0
  58. package/dist/types/cose/cose-key.d.ts.map +1 -0
  59. package/dist/types/cose/cose-sign1.d.ts +195 -0
  60. package/dist/types/cose/cose-sign1.d.ts.map +1 -0
  61. package/dist/types/cose/eat.d.ts +203 -0
  62. package/dist/types/cose/eat.d.ts.map +1 -0
  63. package/dist/types/crypto-error.d.ts +4 -0
  64. package/dist/types/crypto-error.d.ts.map +1 -1
  65. package/dist/types/index.d.ts +9 -0
  66. package/dist/types/index.d.ts.map +1 -1
  67. package/dist/types/local-key-manager.d.ts +4 -4
  68. package/dist/types/local-key-manager.d.ts.map +1 -1
  69. package/dist/types/primitives/ecies-secp256k1.d.ts +53 -0
  70. package/dist/types/primitives/ecies-secp256k1.d.ts.map +1 -0
  71. package/dist/types/primitives/x25519.d.ts +9 -16
  72. package/dist/types/primitives/x25519.d.ts.map +1 -1
  73. package/dist/types/types/crypto-api.d.ts +52 -4
  74. package/dist/types/types/crypto-api.d.ts.map +1 -1
  75. package/dist/types/types/key-converter.d.ts +37 -15
  76. package/dist/types/types/key-converter.d.ts.map +1 -1
  77. package/dist/types/types/key-deriver.d.ts +41 -0
  78. package/dist/types/types/key-deriver.d.ts.map +1 -1
  79. package/dist/types/types/key-io.d.ts +37 -0
  80. package/dist/types/types/key-io.d.ts.map +1 -1
  81. package/dist/types/types/params-direct.d.ts +17 -0
  82. package/dist/types/types/params-direct.d.ts.map +1 -1
  83. package/dist/types/types/params-kms.d.ts +55 -0
  84. package/dist/types/types/params-kms.d.ts.map +1 -1
  85. package/dist/types/utils.d.ts +19 -0
  86. package/dist/types/utils.d.ts.map +1 -1
  87. package/dist/utils.js +1 -1
  88. package/dist/utils.js.map +3 -3
  89. package/package.json +12 -14
  90. package/src/algorithms/aes-ctr.ts +1 -1
  91. package/src/algorithms/aes-gcm.ts +38 -2
  92. package/src/algorithms/aes-kw.ts +182 -0
  93. package/src/algorithms/ecdsa.ts +132 -1
  94. package/src/algorithms/eddsa.ts +108 -1
  95. package/src/algorithms/hkdf.ts +54 -0
  96. package/src/algorithms/pbkdf2.ts +57 -0
  97. package/src/algorithms/sha-2.ts +1 -1
  98. package/src/algorithms/x25519.ts +153 -0
  99. package/src/cose/cbor.ts +36 -0
  100. package/src/cose/cose-key.ts +344 -0
  101. package/src/cose/cose-sign1.ts +473 -0
  102. package/src/cose/eat.ts +368 -0
  103. package/src/crypto-error.ts +6 -0
  104. package/src/index.ts +10 -0
  105. package/src/local-key-manager.ts +9 -4
  106. package/src/primitives/ecies-secp256k1.ts +113 -0
  107. package/src/primitives/x25519.ts +9 -16
  108. package/src/types/crypto-api.ts +124 -6
  109. package/src/types/key-converter.ts +33 -7
  110. package/src/types/key-deriver.ts +49 -0
  111. package/src/types/key-io.ts +40 -0
  112. package/src/types/params-direct.ts +21 -0
  113. package/src/types/params-kms.ts +67 -0
  114. package/src/utils.ts +53 -0
  115. package/dist/browser.js +0 -60
  116. package/dist/browser.js.map +0 -7
@@ -0,0 +1,368 @@
1
+ import type { CoseSign1ProtectedHeader } from './cose-sign1.js';
2
+ import type { Jwk } from '../jose/jwk.js';
3
+
4
+ import { Cbor } from './cbor.js';
5
+ import { CoseSign1 } from './cose-sign1.js';
6
+ import { CryptoError, CryptoErrorCode } from '../crypto-error.js';
7
+
8
+ /**
9
+ * EAT (Entity Attestation Token) claim key constants.
10
+ *
11
+ * EAT reuses CWT registered claim keys and adds attestation-specific claims.
12
+ *
13
+ * @see {@link https://www.rfc-editor.org/rfc/rfc9711 | RFC 9711 — Entity Attestation Token (EAT)}
14
+ * @see {@link https://www.rfc-editor.org/rfc/rfc8392 | RFC 8392 — CWT (CBOR Web Token)}
15
+ */
16
+ export enum EatClaimKey {
17
+ /** Issuer (iss) — RFC 8392 */
18
+ Iss = 1,
19
+ /** Subject (sub) — RFC 8392 */
20
+ Sub = 2,
21
+ /** Audience (aud) — RFC 8392 */
22
+ Aud = 3,
23
+ /** Expiration Time (exp) — RFC 8392 */
24
+ Exp = 4,
25
+ /** Not Before (nbf) — RFC 8392 */
26
+ Nbf = 5,
27
+ /** Issued At (iat) — RFC 8392 */
28
+ Iat = 6,
29
+ /** CWT ID (cti) — RFC 8392 */
30
+ Cti = 7,
31
+ /** Nonce (eat_nonce) — RFC 9711, Section 4.1 */
32
+ Nonce = 10,
33
+ /** UEID (Universal Entity ID) — RFC 9711, Section 4.2.1 */
34
+ Ueid = 256,
35
+ /** SUEIDs (Semi-permanent UEIDs) — RFC 9711, Section 4.2.2 */
36
+ Sueids = 257,
37
+ /** OEM ID (Hardware OEM Identification) — RFC 9711, Section 4.2.3 */
38
+ Oemid = 258,
39
+ /** Hardware Model — RFC 9711, Section 4.2.4 */
40
+ Hwmodel = 259,
41
+ /** Hardware Version — RFC 9711, Section 4.2.5 */
42
+ Hwversion = 260,
43
+ /** Secure Boot — RFC 9711, Section 4.2.7 */
44
+ Secboot = 262,
45
+ /** Debug Status — RFC 9711, Section 4.2.8 */
46
+ Dbgstat = 263,
47
+ /** Location — RFC 9711, Section 4.2.9 */
48
+ Location = 264,
49
+ /** Profile — RFC 9711, Section 4.2.10 */
50
+ Profile = 265,
51
+ /** Submods (Submodules) — RFC 9711, Section 4.2.18 */
52
+ Submods = 266,
53
+ /** Measurement Results — RFC 9711, Section 4.2.15 */
54
+ Measres = 272,
55
+ /** Intended Use — RFC 9711, Section 4.2.14 */
56
+ Intuse = 268,
57
+ }
58
+
59
+ /**
60
+ * Debug status values for the `dbgstat` claim.
61
+ *
62
+ * @see {@link https://www.rfc-editor.org/rfc/rfc9711#section-4.2.8 | RFC 9711, Section 4.2.8}
63
+ */
64
+ export enum EatDebugStatus {
65
+ /** Debug is enabled */
66
+ Enabled = 0,
67
+ /** Debug is disabled */
68
+ Disabled = 1,
69
+ /** Debug is disabled since manufacture */
70
+ DisabledSinceBoot = 2,
71
+ /** Debug is disabled permanently */
72
+ DisabledPermanently = 3,
73
+ /** Debug is disabled fully and permanently */
74
+ DisabledFullyAndPermanently = 4,
75
+ }
76
+
77
+ /**
78
+ * Security level for the `seclevel` claim.
79
+ *
80
+ * @see {@link https://www.rfc-editor.org/rfc/rfc9711#section-4.2.6 | RFC 9711, Section 4.2.6}
81
+ */
82
+ export enum EatSecurityLevel {
83
+ /** Unrestricted — no security guarantees */
84
+ Unrestricted = 1,
85
+ /** Restricted — some restrictions on environment */
86
+ Restricted = 2,
87
+ /** Secure Restricted — hardware-enforced restrictions */
88
+ SecureRestricted = 3,
89
+ /** Hardware — hardware-isolated execution environment */
90
+ Hardware = 4,
91
+ }
92
+
93
+ /**
94
+ * Parsed EAT claims, providing typed access to standard and attestation-specific claims.
95
+ *
96
+ * All fields are optional because EAT does not mandate any specific claims; the
97
+ * required set depends on the attestation profile.
98
+ *
99
+ * @see {@link https://www.rfc-editor.org/rfc/rfc9711 | RFC 9711}
100
+ */
101
+ export interface EatClaims {
102
+ /** Issuer — identifies the entity that issued the token. */
103
+ iss?: string;
104
+
105
+ /** Subject — identifies the entity that is the subject of the token. */
106
+ sub?: string;
107
+
108
+ /** Audience — identifies the intended recipient(s). */
109
+ aud?: string;
110
+
111
+ /** Expiration time (seconds since epoch). */
112
+ exp?: number;
113
+
114
+ /** Not Before (seconds since epoch). */
115
+ nbf?: number;
116
+
117
+ /** Issued At (seconds since epoch). */
118
+ iat?: number;
119
+
120
+ /** CWT ID — unique token identifier (byte string). */
121
+ cti?: Uint8Array;
122
+
123
+ /** Nonce — challenge value binding the token to a request. */
124
+ nonce?: Uint8Array | Uint8Array[];
125
+
126
+ /** Universal Entity ID. */
127
+ ueid?: Uint8Array;
128
+
129
+ /** Hardware model identifier. */
130
+ hwmodel?: Uint8Array;
131
+
132
+ /** Hardware version. */
133
+ hwversion?: unknown;
134
+
135
+ /** Debug status. */
136
+ dbgstat?: EatDebugStatus;
137
+
138
+ /** Measurement results — software component measurements. */
139
+ measres?: unknown;
140
+
141
+ /** Submodules — nested EAT tokens or claims from sub-components. */
142
+ submods?: Map<string, unknown>;
143
+
144
+ /**
145
+ * All raw claims as a Map for access to non-standard or profile-specific claims.
146
+ * Integer keys correspond to {@link EatClaimKey} values.
147
+ */
148
+ rawClaims: Map<number | string, unknown>;
149
+ }
150
+
151
+ /**
152
+ * Parameters for decoding an EAT token.
153
+ */
154
+ export interface EatDecodeParams {
155
+ /** The CBOR-encoded EAT token (COSE_Sign1 envelope). */
156
+ token: Uint8Array;
157
+ }
158
+
159
+ /**
160
+ * Parameters for verifying and decoding an EAT token.
161
+ */
162
+ export interface EatVerifyParams {
163
+ /** The CBOR-encoded EAT token (COSE_Sign1 envelope). */
164
+ token: Uint8Array;
165
+
166
+ /** The public key for signature verification, in JWK format. */
167
+ key: Jwk;
168
+
169
+ /** External additional authenticated data. Defaults to empty bytes. */
170
+ externalAad?: Uint8Array;
171
+ }
172
+
173
+ /**
174
+ * Result of decoding an EAT token.
175
+ */
176
+ export interface EatDecodeResult {
177
+ /** The parsed protected header from the COSE_Sign1 envelope. */
178
+ protectedHeader: CoseSign1ProtectedHeader;
179
+
180
+ /** The parsed EAT claims from the payload. */
181
+ claims: EatClaims;
182
+ }
183
+
184
+ /**
185
+ * Entity Attestation Token (EAT) implementation per RFC 9711.
186
+ *
187
+ * EATs are CBOR-based attestation tokens carried in COSE_Sign1 envelopes.
188
+ * They are used by TEE platforms (ARM CCA, Intel TDX, AMD SEV-SNP, Nitro Enclaves)
189
+ * to provide hardware-rooted attestation evidence.
190
+ *
191
+ * This implementation focuses on decoding and verification of EAT tokens — the
192
+ * primary use case for a DWN node that needs to verify TEE attestation from
193
+ * compute modules.
194
+ *
195
+ * @see {@link https://www.rfc-editor.org/rfc/rfc9711 | RFC 9711 — Entity Attestation Token (EAT)}
196
+ */
197
+ export class Eat {
198
+ /**
199
+ * Decodes an EAT token without verifying its signature.
200
+ *
201
+ * Use this method only when signature verification is performed separately
202
+ * (e.g., by a TEE attestation service) or for debugging/inspection.
203
+ *
204
+ * @param params - The parameters for decoding.
205
+ * @returns The decoded protected header and claims.
206
+ * @throws {CryptoError} If the token is not valid COSE_Sign1 or the payload is not valid CBOR.
207
+ */
208
+ public static decode({ token }: EatDecodeParams): EatDecodeResult {
209
+ // Decode the COSE_Sign1 envelope.
210
+ const coseSign1 = CoseSign1.decode(token);
211
+
212
+ if (coseSign1.payload === null) {
213
+ throw new CryptoError(
214
+ CryptoErrorCode.InvalidEat,
215
+ 'Eat: token has detached payload; use verifyAndDecode with the payload provided separately'
216
+ );
217
+ }
218
+
219
+ // Decode the CBOR payload into claims.
220
+ const claims = Eat.parseClaims(coseSign1.payload);
221
+
222
+ return {
223
+ protectedHeader: coseSign1.protectedHeader,
224
+ claims,
225
+ };
226
+ }
227
+
228
+ /**
229
+ * Verifies the signature of an EAT token and decodes its claims.
230
+ *
231
+ * This is the primary method for processing EAT tokens from TEE attestation.
232
+ * It verifies the COSE_Sign1 signature using the provided public key, then
233
+ * parses the EAT claims from the payload.
234
+ *
235
+ * @param params - The parameters for verification and decoding.
236
+ * @returns The decoded protected header and claims if verification succeeds.
237
+ * @throws {CryptoError} If verification fails or the token is malformed.
238
+ */
239
+ public static async verifyAndDecode(params: EatVerifyParams): Promise<EatDecodeResult> {
240
+ const { token, key, externalAad } = params;
241
+
242
+ // Verify the COSE_Sign1 signature.
243
+ const isValid = await CoseSign1.verify({
244
+ coseSign1: token,
245
+ key,
246
+ externalAad,
247
+ });
248
+
249
+ if (!isValid) {
250
+ throw new CryptoError(
251
+ CryptoErrorCode.InvalidEat,
252
+ 'Eat: signature verification failed'
253
+ );
254
+ }
255
+
256
+ // Decode and return claims (signature is already verified).
257
+ return Eat.decode({ token });
258
+ }
259
+
260
+ /**
261
+ * Parses CBOR-encoded EAT claims into a typed {@link EatClaims} object.
262
+ *
263
+ * Handles both integer-keyed (CBOR standard) and string-keyed claims.
264
+ *
265
+ * @param payload - The CBOR-encoded claims byte string.
266
+ * @returns The parsed EAT claims.
267
+ * @throws {CryptoError} If the payload is not valid CBOR or not a map.
268
+ */
269
+ private static parseClaims(payload: Uint8Array): EatClaims {
270
+ let rawClaims: Map<number | string, unknown>;
271
+
272
+ try {
273
+ const decoded = Cbor.decode<unknown>(payload);
274
+ if (decoded instanceof Map) {
275
+ rawClaims = decoded as Map<number | string, unknown>;
276
+ } else if (typeof decoded === 'object' && decoded !== null) {
277
+ // Some encoders produce plain objects instead of Maps for maps with string keys.
278
+ rawClaims = new Map(Object.entries(decoded));
279
+ } else {
280
+ throw new Error('not a map');
281
+ }
282
+ } catch (error) {
283
+ if (error instanceof CryptoError) {
284
+ throw error;
285
+ }
286
+ throw new CryptoError(
287
+ CryptoErrorCode.InvalidEat,
288
+ 'Eat: payload is not a valid CBOR map'
289
+ );
290
+ }
291
+
292
+ const claims: EatClaims = { rawClaims };
293
+
294
+ // Extract standard CWT claims.
295
+ const iss = rawClaims.get(EatClaimKey.Iss);
296
+ if (iss !== undefined) {
297
+ claims.iss = iss as string;
298
+ }
299
+
300
+ const sub = rawClaims.get(EatClaimKey.Sub);
301
+ if (sub !== undefined) {
302
+ claims.sub = sub as string;
303
+ }
304
+
305
+ const aud = rawClaims.get(EatClaimKey.Aud);
306
+ if (aud !== undefined) {
307
+ claims.aud = aud as string;
308
+ }
309
+
310
+ const exp = rawClaims.get(EatClaimKey.Exp);
311
+ if (exp !== undefined) {
312
+ claims.exp = exp as number;
313
+ }
314
+
315
+ const nbf = rawClaims.get(EatClaimKey.Nbf);
316
+ if (nbf !== undefined) {
317
+ claims.nbf = nbf as number;
318
+ }
319
+
320
+ const iat = rawClaims.get(EatClaimKey.Iat);
321
+ if (iat !== undefined) {
322
+ claims.iat = iat as number;
323
+ }
324
+
325
+ const cti = rawClaims.get(EatClaimKey.Cti);
326
+ if (cti !== undefined) {
327
+ claims.cti = cti as Uint8Array;
328
+ }
329
+
330
+ // Extract EAT-specific claims.
331
+ const nonce = rawClaims.get(EatClaimKey.Nonce);
332
+ if (nonce !== undefined) {
333
+ claims.nonce = nonce as Uint8Array | Uint8Array[];
334
+ }
335
+
336
+ const ueid = rawClaims.get(EatClaimKey.Ueid);
337
+ if (ueid !== undefined) {
338
+ claims.ueid = ueid as Uint8Array;
339
+ }
340
+
341
+ const hwmodel = rawClaims.get(EatClaimKey.Hwmodel);
342
+ if (hwmodel !== undefined) {
343
+ claims.hwmodel = hwmodel as Uint8Array;
344
+ }
345
+
346
+ const hwversion = rawClaims.get(EatClaimKey.Hwversion);
347
+ if (hwversion !== undefined) {
348
+ claims.hwversion = hwversion;
349
+ }
350
+
351
+ const dbgstat = rawClaims.get(EatClaimKey.Dbgstat);
352
+ if (dbgstat !== undefined) {
353
+ claims.dbgstat = dbgstat as EatDebugStatus;
354
+ }
355
+
356
+ const measres = rawClaims.get(EatClaimKey.Measres);
357
+ if (measres !== undefined) {
358
+ claims.measres = measres;
359
+ }
360
+
361
+ const submods = rawClaims.get(EatClaimKey.Submods);
362
+ if (submods !== undefined) {
363
+ claims.submods = submods as Map<string, unknown>;
364
+ }
365
+
366
+ return claims;
367
+ }
368
+ }
@@ -34,6 +34,12 @@ export enum CryptoErrorCode {
34
34
  /** The encoding operation (either encoding or decoding) failed. */
35
35
  EncodingError = 'encodingError',
36
36
 
37
+ /** The COSE_Sign1 message does not conform to valid structure. */
38
+ InvalidCoseSign1 = 'invalidCoseSign1',
39
+
40
+ /** The EAT (Entity Attestation Token) is malformed or failed verification. */
41
+ InvalidEat = 'invalidEat',
42
+
37
43
  /** The JWE supplied does not conform to valid syntax. */
38
44
  InvalidJwe = 'invalidJwe',
39
45
 
package/src/index.ts CHANGED
@@ -2,12 +2,21 @@ export * from './crypto-error.js';
2
2
  export * from './local-key-manager.js';
3
3
  export * from './utils.js';
4
4
 
5
+ export * from './cose/cbor.js';
6
+ export * from './cose/cose-key.js';
7
+ export * from './cose/cose-sign1.js';
8
+ export * from './cose/eat.js';
9
+
5
10
  export * from './algorithms/aes-ctr.js';
6
11
  export * from './algorithms/aes-gcm.js';
12
+ export * from './algorithms/aes-kw.js';
7
13
  export * from './algorithms/crypto-algorithm.js';
8
14
  export * from './algorithms/ecdsa.js';
9
15
  export * from './algorithms/eddsa.js';
16
+ export * from './algorithms/hkdf.js';
17
+ export * from './algorithms/pbkdf2.js';
10
18
  export * from './algorithms/sha-2.js';
19
+ export * from './algorithms/x25519.js';
11
20
 
12
21
  export * from './jose/jwe.js';
13
22
  export * from './jose/jwk.js';
@@ -19,6 +28,7 @@ export * from './primitives/aes-ctr.js';
19
28
  export * from './primitives/aes-gcm.js';
20
29
  export * from './primitives/aes-kw.js';
21
30
  export * from './primitives/concat-kdf.js';
31
+ export * from './primitives/ecies-secp256k1.js';
22
32
  export * from './primitives/ed25519.js';
23
33
  export * from './primitives/hkdf.js';
24
34
  export * from './primitives/secp256r1.js';
@@ -2,11 +2,11 @@ import type { KeyValueStore } from '@enbox/common';
2
2
  import { MemoryStore } from '@enbox/common';
3
3
 
4
4
  import type { CryptoAlgorithm } from './algorithms/crypto-algorithm.js';
5
- import type { CryptoApi } from './types/crypto-api.js';
6
5
  import type { Hasher } from './types/hasher.js';
7
6
  import type { Jwk } from './jose/jwk.js';
8
7
  import type { KeyIdentifier } from './types/identifier.js';
9
8
  import type { KeyImporterExporter } from './types/key-io.js';
9
+ import type { KeyManager } from './types/crypto-api.js';
10
10
  import type { Signer } from './types/signer.js';
11
11
  import type { AsymmetricKeyGenerator, KeyGenerator } from './types/key-generator.js';
12
12
  import type { GetPublicKeyParams, SignParams, VerifyParams } from './types/params-direct.js';
@@ -24,6 +24,7 @@ import type {
24
24
  import { EcdsaAlgorithm } from './algorithms/ecdsa.js';
25
25
  import { EdDsaAlgorithm } from './algorithms/eddsa.js';
26
26
  import { Sha2Algorithm } from './algorithms/sha-2.js';
27
+ import { X25519Algorithm } from './algorithms/x25519.js';
27
28
  import { computeJwkThumbprint, isPrivateJwk, KEY_URI_PREFIX_JWK } from './jose/jwk.js';
28
29
 
29
30
  /**
@@ -50,6 +51,10 @@ const supportedAlgorithms = {
50
51
  'SHA-256': {
51
52
  implementation : Sha2Algorithm,
52
53
  names : ['SHA-256']
54
+ },
55
+ 'X25519': {
56
+ implementation : X25519Algorithm,
57
+ names : ['X25519']
53
58
  }
54
59
  } satisfies {
55
60
  [key: string]: {
@@ -104,11 +109,11 @@ export interface LocalKeyManagerGenerateKeyParams extends KmsGenerateKeyParams {
104
109
  * - `"Ed25519"`
105
110
  * - `"secp256k1"`
106
111
  */
107
- algorithm: 'Ed25519' | 'secp256k1' | 'secp256r1';
112
+ algorithm: 'Ed25519' | 'secp256k1' | 'secp256r1' | 'X25519';
108
113
  }
109
114
 
110
115
  export class LocalKeyManager implements
111
- CryptoApi,
116
+ KeyManager,
112
117
  KeyImporterExporter<KmsImportKeyParams, KeyIdentifier, KmsExportKeyParams> {
113
118
 
114
119
  /**
@@ -242,7 +247,7 @@ export class LocalKeyManager implements
242
247
  * @remarks
243
248
  * This method generates a {@link https://datatracker.ietf.org/doc/html/rfc3986 | URI}
244
249
  * (Uniform Resource Identifier) for the given JWK, which uniquely identifies the key across all
245
- * `CryptoApi` implementations. The key URI is constructed by appending the
250
+ * `KeyManager` implementations. The key URI is constructed by appending the
246
251
  * {@link https://datatracker.ietf.org/doc/html/rfc7638 | JWK thumbprint} to the prefix
247
252
  * `urn:jwk:`. The JWK thumbprint is deterministically computed from the JWK and is consistent
248
253
  * regardless of property order or optional property inclusion in the JWK. This ensures that the
@@ -0,0 +1,113 @@
1
+ import { concatBytes } from '@noble/ciphers/utils';
2
+ import { gcm } from '@noble/ciphers/aes';
3
+ import { hkdf } from '@noble/hashes/hkdf';
4
+ import { randomBytes } from '@noble/ciphers/webcrypto';
5
+ import { secp256k1 } from '@noble/curves/secp256k1';
6
+ import { sha256 } from '@noble/hashes/sha256';
7
+
8
+ /**
9
+ * AEAD tag length for AES-256-GCM (16 bytes / 128 bits).
10
+ */
11
+ const AEAD_TAG_LENGTH = 16;
12
+
13
+ /**
14
+ * Nonce length for AES-256-GCM encryption.
15
+ */
16
+ const NONCE_LENGTH = 16;
17
+
18
+ /**
19
+ * Output of an ECIES-SECP256K1 encryption operation.
20
+ */
21
+ export type EciesSecp256k1EncryptionOutput = {
22
+ /** The AES-GCM initialization vector. */
23
+ initializationVector: Uint8Array;
24
+ /** The ephemeral secp256k1 public key (compressed, 33 bytes). */
25
+ ephemeralPublicKey: Uint8Array;
26
+ /** The encrypted data. */
27
+ ciphertext: Uint8Array;
28
+ /** The AES-GCM authentication tag (16 bytes). */
29
+ messageAuthenticationCode: Uint8Array;
30
+ };
31
+
32
+ /**
33
+ * Input required for ECIES-SECP256K1 decryption.
34
+ */
35
+ export type EciesSecp256k1EncryptionInput = EciesSecp256k1EncryptionOutput & {
36
+ /** The recipient's secp256k1 private key (raw 32 bytes). */
37
+ privateKey: Uint8Array;
38
+ };
39
+
40
+ /**
41
+ * Browser-compatible ECIES (Elliptic Curve Integrated Encryption Scheme) using secp256k1.
42
+ *
43
+ * Wire-format compatible with `eciesjs` v0.4.x configured with
44
+ * `isEphemeralKeyCompressed: true, isHkdfKeyCompressed: false` (the default).
45
+ *
46
+ * Protocol:
47
+ * 1. Generate an ephemeral secp256k1 key pair.
48
+ * 2. ECDH shared secret (uncompressed point).
49
+ * 3. HKDF-SHA-256 key derivation: `hkdf(sha256, ephemeralPubUncompressed || sharedPointUncompressed)`.
50
+ * 4. AES-256-GCM encryption with random 16-byte nonce.
51
+ *
52
+ * All underlying primitives (`@noble/ciphers`, `@noble/curves`, `@noble/hashes`)
53
+ * are pure JavaScript and work in Node, Bun, and browsers.
54
+ */
55
+ export class EciesSecp256k1 {
56
+ /**
57
+ * Encrypt plaintext for a given secp256k1 public key.
58
+ * @param publicKeyBytes - Recipient's public key (compressed 33 bytes or uncompressed 65 bytes).
59
+ * @param plaintext - The data to encrypt.
60
+ */
61
+ public static encrypt(publicKeyBytes: Uint8Array, plaintext: Uint8Array): EciesSecp256k1EncryptionOutput {
62
+ // Generate ephemeral key pair.
63
+ const ephemeralPrivateKey = secp256k1.utils.randomPrivateKey();
64
+ const ephemeralPubCompressed = secp256k1.getPublicKey(ephemeralPrivateKey, true);
65
+ const ephemeralPubUncompressed = secp256k1.getPublicKey(ephemeralPrivateKey, false);
66
+
67
+ // ECDH: shared point (uncompressed).
68
+ const sharedPointUncompressed = secp256k1.getSharedSecret(ephemeralPrivateKey, publicKeyBytes, false);
69
+
70
+ // HKDF-SHA-256: derive 32-byte symmetric key.
71
+ // eciesjs (isHkdfKeyCompressed=false): master = senderPubUncompressed || sharedPointUncompressed
72
+ const symmetricKey = hkdf(sha256, concatBytes(ephemeralPubUncompressed, sharedPointUncompressed), undefined, undefined, 32);
73
+
74
+ // AES-256-GCM encrypt.
75
+ const nonce = randomBytes(NONCE_LENGTH);
76
+ const ciphered = gcm(symmetricKey, nonce).encrypt(plaintext); // ciphertext || tag
77
+
78
+ return {
79
+ ephemeralPublicKey : ephemeralPubCompressed,
80
+ initializationVector : nonce,
81
+ messageAuthenticationCode : ciphered.subarray(ciphered.length - AEAD_TAG_LENGTH),
82
+ ciphertext : ciphered.subarray(0, ciphered.length - AEAD_TAG_LENGTH),
83
+ };
84
+ }
85
+
86
+ /**
87
+ * Decrypt ciphertext produced by {@link EciesSecp256k1.encrypt}.
88
+ * @param input - The encryption output plus the recipient's private key.
89
+ */
90
+ public static decrypt(input: EciesSecp256k1EncryptionInput): Uint8Array {
91
+ const { privateKey, ephemeralPublicKey, initializationVector, messageAuthenticationCode, ciphertext } = input;
92
+
93
+ // Decompress ephemeral public key (HKDF needs uncompressed form).
94
+ const ephemeralPubUncompressed = secp256k1.ProjectivePoint.fromHex(ephemeralPublicKey).toRawBytes(false);
95
+
96
+ // ECDH: shared point (uncompressed).
97
+ const sharedPointUncompressed = secp256k1.getSharedSecret(privateKey, ephemeralPublicKey, false);
98
+
99
+ // HKDF-SHA-256: derive 32-byte symmetric key (same derivation as encrypt).
100
+ const symmetricKey = hkdf(sha256, concatBytes(ephemeralPubUncompressed, sharedPointUncompressed), undefined, undefined, 32);
101
+
102
+ // AES-256-GCM decrypt: reconstruct the wire format (ciphertext || tag).
103
+ const ciphered = concatBytes(ciphertext, messageAuthenticationCode);
104
+ return gcm(symmetricKey, Uint8Array.from(initializationVector)).decrypt(ciphered);
105
+ }
106
+
107
+ /**
108
+ * Whether the ephemeral public key is compressed (always true for this implementation).
109
+ */
110
+ public static get isEphemeralKeyCompressed(): boolean {
111
+ return true;
112
+ }
113
+ }
@@ -345,32 +345,25 @@ export class X25519 {
345
345
  }
346
346
 
347
347
  /**
348
- * Computes an RFC6090-compliant Elliptic Curve Diffie-Hellman (ECDH) shared secret
349
- * using secp256k1 private and public keys in JSON Web Key (JWK) format.
348
+ * Computes an X25519 Elliptic Curve Diffie-Hellman (ECDH) shared secret
349
+ * using X25519 private and public keys in JSON Web Key (JWK) format.
350
350
  *
351
351
  * @remarks
352
352
  * This method facilitates the ECDH key agreement protocol, which is a method of securely
353
353
  * deriving a shared secret between two parties based on their private and public keys.
354
354
  * It takes the private key of one party (privateKeyA) and the public key of another
355
- * party (publicKeyB) to compute a shared secret. The shared secret is derived from the
356
- * x-coordinate of the elliptic curve point resulting from the multiplication of the
357
- * public key with the private key.
358
- *
359
- * Note: When performing Elliptic Curve Diffie-Hellman (ECDH) key agreement,
360
- * the resulting shared secret is a point on the elliptic curve, which
361
- * consists of an x-coordinate and a y-coordinate. With a 256-bit curve like
362
- * secp256k1, each of these coordinates is 32 bytes (256 bits) long. However,
363
- * in the ECDH process, it's standard practice to use only the x-coordinate
364
- * of the shared secret point as the resulting shared key. This is because
365
- * the y-coordinate does not add to the entropy of the key, and both parties
366
- * can independently compute the x-coordinate. Consquently, this implementation
367
- * omits the y-coordinate for simplicity and standard compliance.
355
+ * party (publicKeyB) to compute a shared secret. The shared secret is the raw output
356
+ * of the X25519 function as defined in RFC 7748.
357
+ *
358
+ * Note: Unlike Weierstrass curves (e.g., secp256k1), X25519 is a Montgomery curve
359
+ * where the ECDH output is a single 32-byte scalar value, not an (x, y) point.
360
+ * The result is used directly as the shared secret.
368
361
  *
369
362
  * @example
370
363
  * ```ts
371
364
  * const privateKeyA = { ... }; // A Jwk object for party A
372
365
  * const publicKeyB = { ... }; // A PublicKeyJwk object for party B
373
- * const sharedSecret = await Secp256k1.sharedSecret({
366
+ * const sharedSecret = await X25519.sharedSecret({
374
367
  * privateKeyA,
375
368
  * publicKeyB
376
369
  * });