@opentdf/sdk 0.9.0-beta.91 → 0.9.0-beta.93

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 (182) hide show
  1. package/dist/cjs/src/access/access-fetch.js +1 -2
  2. package/dist/cjs/src/access/access-rpc.js +1 -3
  3. package/dist/cjs/src/access.js +1 -14
  4. package/dist/cjs/src/auth/auth.js +13 -10
  5. package/dist/cjs/src/auth/dpop.js +121 -0
  6. package/dist/cjs/src/auth/oidc-clientcredentials-provider.js +37 -3
  7. package/dist/cjs/src/auth/oidc-externaljwt-provider.js +37 -3
  8. package/dist/cjs/src/auth/oidc-refreshtoken-provider.js +37 -3
  9. package/dist/cjs/src/auth/oidc.js +10 -8
  10. package/dist/cjs/src/auth/providers.js +35 -12
  11. package/dist/cjs/src/crypto/index.js +16 -2
  12. package/dist/cjs/src/crypto/pemPublicToCrypto.js +17 -11
  13. package/dist/cjs/src/opentdf.js +40 -10
  14. package/dist/cjs/tdf3/index.js +4 -2
  15. package/dist/cjs/tdf3/src/assertions.js +71 -31
  16. package/dist/cjs/tdf3/src/ciphers/aes-gcm-cipher.js +1 -1
  17. package/dist/cjs/tdf3/src/ciphers/symmetric-cipher-base.js +4 -2
  18. package/dist/cjs/tdf3/src/client/index.js +23 -33
  19. package/dist/cjs/tdf3/src/crypto/crypto-utils.js +12 -5
  20. package/dist/cjs/tdf3/src/crypto/declarations.js +1 -1
  21. package/dist/cjs/tdf3/src/crypto/index.js +849 -88
  22. package/dist/cjs/tdf3/src/crypto/jose/jwt-claims-set.js +11 -0
  23. package/dist/cjs/tdf3/src/crypto/jose/validate-crit.js +8 -0
  24. package/dist/cjs/tdf3/src/crypto/jose/vendor/lib/buffer_utils.js +41 -0
  25. package/dist/cjs/tdf3/src/crypto/jose/vendor/lib/epoch.js +6 -0
  26. package/dist/cjs/tdf3/src/crypto/jose/vendor/lib/is_object.js +21 -0
  27. package/dist/cjs/tdf3/src/crypto/jose/vendor/lib/jwt_claims_set.js +112 -0
  28. package/dist/cjs/tdf3/src/crypto/jose/vendor/lib/secs.js +60 -0
  29. package/dist/cjs/tdf3/src/crypto/jose/vendor/lib/validate_crit.js +38 -0
  30. package/dist/cjs/tdf3/src/crypto/jose/vendor/util/errors.js +135 -0
  31. package/dist/cjs/tdf3/src/crypto/jwt.js +183 -0
  32. package/dist/cjs/tdf3/src/crypto/salt.js +14 -8
  33. package/dist/cjs/tdf3/src/models/encryption-information.js +17 -20
  34. package/dist/cjs/tdf3/src/models/key-access.js +43 -63
  35. package/dist/cjs/tdf3/src/tdf.js +75 -75
  36. package/dist/cjs/tdf3/src/utils/index.js +5 -39
  37. package/dist/types/src/access/access-fetch.d.ts.map +1 -1
  38. package/dist/types/src/access/access-rpc.d.ts.map +1 -1
  39. package/dist/types/src/access.d.ts +0 -5
  40. package/dist/types/src/access.d.ts.map +1 -1
  41. package/dist/types/src/auth/auth.d.ts +9 -6
  42. package/dist/types/src/auth/auth.d.ts.map +1 -1
  43. package/dist/types/src/auth/dpop.d.ts +60 -0
  44. package/dist/types/src/auth/dpop.d.ts.map +1 -0
  45. package/dist/types/src/auth/oidc-clientcredentials-provider.d.ts +3 -2
  46. package/dist/types/src/auth/oidc-clientcredentials-provider.d.ts.map +1 -1
  47. package/dist/types/src/auth/oidc-externaljwt-provider.d.ts +3 -2
  48. package/dist/types/src/auth/oidc-externaljwt-provider.d.ts.map +1 -1
  49. package/dist/types/src/auth/oidc-refreshtoken-provider.d.ts +3 -2
  50. package/dist/types/src/auth/oidc-refreshtoken-provider.d.ts.map +1 -1
  51. package/dist/types/src/auth/oidc.d.ts +6 -4
  52. package/dist/types/src/auth/oidc.d.ts.map +1 -1
  53. package/dist/types/src/auth/providers.d.ts +5 -4
  54. package/dist/types/src/auth/providers.d.ts.map +1 -1
  55. package/dist/types/src/crypto/index.d.ts +2 -1
  56. package/dist/types/src/crypto/index.d.ts.map +1 -1
  57. package/dist/types/src/crypto/pemPublicToCrypto.d.ts +18 -0
  58. package/dist/types/src/crypto/pemPublicToCrypto.d.ts.map +1 -1
  59. package/dist/types/src/opentdf.d.ts +13 -4
  60. package/dist/types/src/opentdf.d.ts.map +1 -1
  61. package/dist/types/tdf3/index.d.ts +3 -3
  62. package/dist/types/tdf3/index.d.ts.map +1 -1
  63. package/dist/types/tdf3/src/assertions.d.ts +23 -8
  64. package/dist/types/tdf3/src/assertions.d.ts.map +1 -1
  65. package/dist/types/tdf3/src/ciphers/aes-gcm-cipher.d.ts +3 -3
  66. package/dist/types/tdf3/src/ciphers/aes-gcm-cipher.d.ts.map +1 -1
  67. package/dist/types/tdf3/src/ciphers/symmetric-cipher-base.d.ts +4 -4
  68. package/dist/types/tdf3/src/ciphers/symmetric-cipher-base.d.ts.map +1 -1
  69. package/dist/types/tdf3/src/client/builders.d.ts +2 -2
  70. package/dist/types/tdf3/src/client/builders.d.ts.map +1 -1
  71. package/dist/types/tdf3/src/client/index.d.ts +6 -5
  72. package/dist/types/tdf3/src/client/index.d.ts.map +1 -1
  73. package/dist/types/tdf3/src/crypto/crypto-utils.d.ts +14 -4
  74. package/dist/types/tdf3/src/crypto/crypto-utils.d.ts.map +1 -1
  75. package/dist/types/tdf3/src/crypto/declarations.d.ts +283 -18
  76. package/dist/types/tdf3/src/crypto/declarations.d.ts.map +1 -1
  77. package/dist/types/tdf3/src/crypto/index.d.ts +105 -28
  78. package/dist/types/tdf3/src/crypto/index.d.ts.map +1 -1
  79. package/dist/types/tdf3/src/crypto/jose/jwt-claims-set.d.ts +3 -0
  80. package/dist/types/tdf3/src/crypto/jose/jwt-claims-set.d.ts.map +1 -0
  81. package/dist/types/tdf3/src/crypto/jose/validate-crit.d.ts +5 -0
  82. package/dist/types/tdf3/src/crypto/jose/validate-crit.d.ts.map +1 -0
  83. package/dist/types/tdf3/src/crypto/jose/vendor/lib/buffer_utils.d.ts +6 -0
  84. package/dist/types/tdf3/src/crypto/jose/vendor/lib/buffer_utils.d.ts.map +1 -0
  85. package/dist/types/tdf3/src/crypto/jose/vendor/lib/epoch.d.ts +3 -0
  86. package/dist/types/tdf3/src/crypto/jose/vendor/lib/epoch.d.ts.map +1 -0
  87. package/dist/types/tdf3/src/crypto/jose/vendor/lib/is_object.d.ts +3 -0
  88. package/dist/types/tdf3/src/crypto/jose/vendor/lib/is_object.d.ts.map +1 -0
  89. package/dist/types/tdf3/src/crypto/jose/vendor/lib/jwt_claims_set.d.ts +3 -0
  90. package/dist/types/tdf3/src/crypto/jose/vendor/lib/jwt_claims_set.d.ts.map +1 -0
  91. package/dist/types/tdf3/src/crypto/jose/vendor/lib/secs.d.ts +3 -0
  92. package/dist/types/tdf3/src/crypto/jose/vendor/lib/secs.d.ts.map +1 -0
  93. package/dist/types/tdf3/src/crypto/jose/vendor/lib/validate_crit.d.ts +3 -0
  94. package/dist/types/tdf3/src/crypto/jose/vendor/lib/validate_crit.d.ts.map +1 -0
  95. package/dist/types/tdf3/src/crypto/jose/vendor/util/errors.d.ts +76 -0
  96. package/dist/types/tdf3/src/crypto/jose/vendor/util/errors.d.ts.map +1 -0
  97. package/dist/types/tdf3/src/crypto/jwt.d.ts +76 -0
  98. package/dist/types/tdf3/src/crypto/jwt.d.ts.map +1 -0
  99. package/dist/types/tdf3/src/crypto/salt.d.ts +6 -1
  100. package/dist/types/tdf3/src/crypto/salt.d.ts.map +1 -1
  101. package/dist/types/tdf3/src/models/encryption-information.d.ts +4 -4
  102. package/dist/types/tdf3/src/models/encryption-information.d.ts.map +1 -1
  103. package/dist/types/tdf3/src/models/key-access.d.ts +8 -5
  104. package/dist/types/tdf3/src/models/key-access.d.ts.map +1 -1
  105. package/dist/types/tdf3/src/tdf.d.ts +8 -8
  106. package/dist/types/tdf3/src/tdf.d.ts.map +1 -1
  107. package/dist/types/tdf3/src/utils/index.d.ts +4 -3
  108. package/dist/types/tdf3/src/utils/index.d.ts.map +1 -1
  109. package/dist/web/src/access/access-fetch.js +3 -4
  110. package/dist/web/src/access/access-rpc.js +3 -5
  111. package/dist/web/src/access.js +1 -13
  112. package/dist/web/src/auth/auth.js +13 -10
  113. package/dist/web/src/auth/dpop.js +118 -0
  114. package/dist/web/src/auth/oidc-clientcredentials-provider.js +4 -3
  115. package/dist/web/src/auth/oidc-externaljwt-provider.js +4 -3
  116. package/dist/web/src/auth/oidc-refreshtoken-provider.js +4 -3
  117. package/dist/web/src/auth/oidc.js +11 -9
  118. package/dist/web/src/auth/providers.js +13 -12
  119. package/dist/web/src/crypto/index.js +4 -2
  120. package/dist/web/src/crypto/pemPublicToCrypto.js +11 -9
  121. package/dist/web/src/opentdf.js +7 -10
  122. package/dist/web/tdf3/index.js +3 -2
  123. package/dist/web/tdf3/src/assertions.js +71 -31
  124. package/dist/web/tdf3/src/ciphers/aes-gcm-cipher.js +1 -1
  125. package/dist/web/tdf3/src/ciphers/symmetric-cipher-base.js +4 -2
  126. package/dist/web/tdf3/src/client/index.js +25 -35
  127. package/dist/web/tdf3/src/crypto/crypto-utils.js +12 -5
  128. package/dist/web/tdf3/src/crypto/declarations.js +1 -1
  129. package/dist/web/tdf3/src/crypto/index.js +830 -84
  130. package/dist/web/tdf3/src/crypto/jose/jwt-claims-set.js +5 -0
  131. package/dist/web/tdf3/src/crypto/jose/validate-crit.js +3 -0
  132. package/dist/web/tdf3/src/crypto/jose/vendor/lib/buffer_utils.js +35 -0
  133. package/dist/web/tdf3/src/crypto/jose/vendor/lib/epoch.js +4 -0
  134. package/dist/web/tdf3/src/crypto/jose/vendor/lib/is_object.js +19 -0
  135. package/dist/web/tdf3/src/crypto/jose/vendor/lib/jwt_claims_set.js +107 -0
  136. package/dist/web/tdf3/src/crypto/jose/vendor/lib/secs.js +58 -0
  137. package/dist/web/tdf3/src/crypto/jose/vendor/lib/validate_crit.js +36 -0
  138. package/dist/web/tdf3/src/crypto/jose/vendor/util/errors.js +117 -0
  139. package/dist/web/tdf3/src/crypto/jwt.js +174 -0
  140. package/dist/web/tdf3/src/crypto/salt.js +13 -7
  141. package/dist/web/tdf3/src/models/encryption-information.js +11 -14
  142. package/dist/web/tdf3/src/models/key-access.js +44 -31
  143. package/dist/web/tdf3/src/tdf.js +71 -71
  144. package/dist/web/tdf3/src/utils/index.js +5 -6
  145. package/package.json +11 -4
  146. package/src/access/access-fetch.ts +2 -8
  147. package/src/access/access-rpc.ts +0 -7
  148. package/src/access.ts +0 -17
  149. package/src/auth/auth.ts +21 -12
  150. package/src/auth/dpop.ts +222 -0
  151. package/src/auth/oidc-clientcredentials-provider.ts +23 -15
  152. package/src/auth/oidc-externaljwt-provider.ts +23 -15
  153. package/src/auth/oidc-refreshtoken-provider.ts +23 -15
  154. package/src/auth/oidc.ts +21 -10
  155. package/src/auth/providers.ts +46 -29
  156. package/src/crypto/index.ts +21 -1
  157. package/src/crypto/pemPublicToCrypto.ts +11 -9
  158. package/src/opentdf.ts +19 -14
  159. package/tdf3/index.ts +32 -5
  160. package/tdf3/src/assertions.ts +99 -30
  161. package/tdf3/src/ciphers/aes-gcm-cipher.ts +7 -2
  162. package/tdf3/src/ciphers/symmetric-cipher-base.ts +7 -4
  163. package/tdf3/src/client/builders.ts +2 -2
  164. package/tdf3/src/client/index.ts +60 -59
  165. package/tdf3/src/crypto/crypto-utils.ts +15 -8
  166. package/tdf3/src/crypto/declarations.ts +338 -22
  167. package/tdf3/src/crypto/index.ts +1021 -118
  168. package/tdf3/src/crypto/jose/jwt-claims-set.ts +10 -0
  169. package/tdf3/src/crypto/jose/validate-crit.ts +9 -0
  170. package/tdf3/src/crypto/jose/vendor/lib/buffer_utils.ts +34 -0
  171. package/tdf3/src/crypto/jose/vendor/lib/epoch.ts +3 -0
  172. package/tdf3/src/crypto/jose/vendor/lib/is_object.ts +18 -0
  173. package/tdf3/src/crypto/jose/vendor/lib/jwt_claims_set.ts +106 -0
  174. package/tdf3/src/crypto/jose/vendor/lib/secs.ts +57 -0
  175. package/tdf3/src/crypto/jose/vendor/lib/validate_crit.ts +35 -0
  176. package/tdf3/src/crypto/jose/vendor/util/errors.ts +101 -0
  177. package/tdf3/src/crypto/jwt.ts +256 -0
  178. package/tdf3/src/crypto/salt.ts +16 -8
  179. package/tdf3/src/models/encryption-information.ts +14 -21
  180. package/tdf3/src/models/key-access.ts +57 -41
  181. package/tdf3/src/tdf.ts +110 -93
  182. package/tdf3/src/utils/index.ts +5 -6
@@ -7,20 +7,38 @@
7
7
  import { Algorithms } from '../ciphers/index.js';
8
8
  import { Binary } from '../binary.js';
9
9
  import {
10
- CryptoService,
11
- DecryptResult,
12
- EncryptResult,
10
+ type AsymmetricSigningAlgorithm,
11
+ type CryptoService,
12
+ type DecryptResult,
13
+ type ECCurve,
14
+ type EncryptResult,
15
+ type HashAlgorithm,
16
+ type HkdfParams,
17
+ type KeyAlgorithm,
18
+ type KeyOptions,
19
+ type KeyPair,
13
20
  MIN_ASYMMETRIC_KEY_SIZE_BITS,
14
- PemKeyPair,
21
+ type PrivateKey,
22
+ type PublicKey,
23
+ type PublicKeyInfo,
24
+ type SymmetricKey,
15
25
  } from './declarations.js';
16
26
  import { ConfigurationError, DecryptError } from '../../../src/errors.js';
17
27
  import { formatAsPem, removePemFormatting } from './crypto-utils.js';
18
28
  import { encodeArrayBuffer as hexEncode } from '../../../src/encodings/hex.js';
19
29
  import { decodeArrayBuffer as base64Decode } from '../../../src/encodings/base64.js';
20
30
  import { AlgorithmUrn } from '../ciphers/algorithms.js';
31
+ import { exportSPKI, importX509 } from 'jose';
32
+ import {
33
+ toJwsAlg,
34
+ guessAlgorithmName,
35
+ guessCurveName,
36
+ } from '../../../src/crypto/pemPublicToCrypto.js';
37
+ import { keySplit, keyMerge } from '../utils/keysplit.js';
21
38
 
22
39
  // Used to pass into native crypto functions
23
- const METHODS: KeyUsage[] = ['encrypt', 'decrypt'];
40
+ const ENC_DEC_METHODS: KeyUsage[] = ['encrypt', 'decrypt'];
41
+ const SIGN_VERIFY_METHODS: KeyUsage[] = ['sign', 'verify'];
24
42
  export const isSupported = typeof globalThis?.crypto !== 'undefined';
25
43
 
26
44
  export const method = 'http://www.w3.org/2001/04/xmlenc#aes256-cbc';
@@ -63,11 +81,97 @@ export function rsaPkcs1Sha256(
63
81
  }
64
82
 
65
83
  /**
66
- * Generate a random hex key
67
- * @return New key as a hex string
84
+ * Generate a random symmetric key (opaque).
85
+ * @param length - Key length in bytes (default 32 for AES-256)
86
+ * @return Opaque symmetric key
87
+ */
88
+ export async function generateKey(length?: number): Promise<SymmetricKey> {
89
+ const keyBytes = await randomBytes(length || 32);
90
+ return wrapSymmetricKey(keyBytes);
91
+ }
92
+
93
+ // ============================================================
94
+ // Opaque Key Wrapping/Unwrapping Helpers
95
+ // ============================================================
96
+
97
+ /**
98
+ * Wrap a CryptoKey as an opaque PublicKey.
99
+ * @internal
68
100
  */
69
- export async function generateKey(length?: number): Promise<string> {
70
- return randomBytesAsHex(length || 32);
101
+ function wrapPublicKey(key: CryptoKey, algorithm: KeyAlgorithm): PublicKey {
102
+ const result: any = {
103
+ _brand: 'PublicKey',
104
+ algorithm,
105
+ _internal: key,
106
+ };
107
+ if (algorithm.startsWith('rsa:')) {
108
+ result.modulusBits = parseInt(algorithm.split(':')[1], 10);
109
+ } else if (algorithm.startsWith('ec:')) {
110
+ const curvePart = algorithm.split(':')[1];
111
+ result.curve =
112
+ curvePart === 'secp256r1'
113
+ ? 'P-256'
114
+ : curvePart === 'secp384r1'
115
+ ? 'P-384'
116
+ : curvePart === 'secp521r1'
117
+ ? 'P-521'
118
+ : undefined;
119
+ }
120
+ return result as PublicKey;
121
+ }
122
+
123
+ /**
124
+ * Wrap a CryptoKey as an opaque PrivateKey.
125
+ * @internal
126
+ */
127
+ function wrapPrivateKey(key: CryptoKey, algorithm: KeyAlgorithm): PrivateKey {
128
+ const result: any = {
129
+ _brand: 'PrivateKey',
130
+ algorithm,
131
+ _internal: key,
132
+ };
133
+ if (algorithm.startsWith('rsa:')) {
134
+ result.modulusBits = parseInt(algorithm.split(':')[1], 10);
135
+ } else if (algorithm.startsWith('ec:')) {
136
+ const curvePart = algorithm.split(':')[1];
137
+ result.curve =
138
+ curvePart === 'secp256r1'
139
+ ? 'P-256'
140
+ : curvePart === 'secp384r1'
141
+ ? 'P-384'
142
+ : curvePart === 'secp521r1'
143
+ ? 'P-521'
144
+ : undefined;
145
+ }
146
+ return result as PrivateKey;
147
+ }
148
+
149
+ /**
150
+ * Unwrap an opaque key to get the internal CryptoKey.
151
+ * @internal
152
+ */
153
+ function unwrapKey(key: PublicKey | PrivateKey): CryptoKey {
154
+ return (key as any)._internal;
155
+ }
156
+
157
+ /**
158
+ * Wrap raw key bytes as an opaque SymmetricKey.
159
+ * @internal
160
+ */
161
+ function wrapSymmetricKey(keyBytes: Uint8Array): SymmetricKey {
162
+ return {
163
+ _brand: 'SymmetricKey',
164
+ length: keyBytes.length * 8, // bits
165
+ _internal: keyBytes,
166
+ } as SymmetricKey;
167
+ }
168
+
169
+ /**
170
+ * Unwrap an opaque SymmetricKey to get raw bytes.
171
+ * @internal
172
+ */
173
+ function unwrapSymmetricKey(key: SymmetricKey): Uint8Array {
174
+ return (key as any)._internal;
71
175
  }
72
176
 
73
177
  /**
@@ -75,79 +179,71 @@ export async function generateKey(length?: number): Promise<string> {
75
179
  * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/generateKey}
76
180
  * @param size in bits
77
181
  */
78
- export async function generateKeyPair(size?: number): Promise<CryptoKeyPair> {
79
- const algoDomString = rsaOaepSha1(size || MIN_ASYMMETRIC_KEY_SIZE_BITS);
80
- return crypto.subtle.generateKey(algoDomString, true, METHODS);
182
+ export async function generateKeyPair(size?: number): Promise<KeyPair> {
183
+ const keySize = size || MIN_ASYMMETRIC_KEY_SIZE_BITS;
184
+ const algoDomString = rsaOaepSha1(keySize);
185
+ const keyPair = await crypto.subtle.generateKey(algoDomString, true, ENC_DEC_METHODS);
186
+
187
+ // Map to supported algorithm sizes
188
+ let algorithm: KeyAlgorithm;
189
+ if (keySize === 2048) {
190
+ algorithm = 'rsa:2048';
191
+ } else if (keySize === 4096) {
192
+ algorithm = 'rsa:4096';
193
+ } else {
194
+ throw new ConfigurationError(
195
+ `Unsupported RSA key size: ${keySize}. Only 2048 and 4096 are supported.`
196
+ );
197
+ }
198
+
199
+ return {
200
+ publicKey: wrapPublicKey(keyPair.publicKey, algorithm),
201
+ privateKey: wrapPrivateKey(keyPair.privateKey, algorithm),
202
+ };
81
203
  }
82
204
 
83
205
  /**
84
206
  * Generate an RSA key pair suitable for signatures
85
207
  * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/generateKey}
86
208
  */
87
- export async function generateSigningKeyPair(): Promise<CryptoKeyPair> {
88
- return crypto.subtle.generateKey(
89
- {
90
- name: 'RSASSA-PKCS1-v1_5',
91
- hash: 'SHA-256',
92
- modulusLength: 2048,
93
- publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
94
- },
95
- true,
96
- ['sign', 'verify']
97
- );
98
- }
209
+ export async function generateSigningKeyPair(): Promise<KeyPair> {
210
+ const rsaParams = rsaPkcs1Sha256(2048);
211
+ const keyPair = await crypto.subtle.generateKey(rsaParams, true, SIGN_VERIFY_METHODS);
99
212
 
100
- export async function cryptoToPemPair(keysMaybe: unknown): Promise<PemKeyPair> {
101
- const keys = keysMaybe as CryptoKeyPair;
102
- if (!keys.privateKey || !keys.publicKey) {
103
- // These are only ever generated here, so this should not happen
104
- throw new Error('internal: invalid keys');
105
- }
106
-
107
- const [exPublic, exPrivate] = await Promise.all([
108
- crypto.subtle.exportKey('spki', keys.publicKey),
109
- crypto.subtle.exportKey('pkcs8', keys.privateKey),
110
- ]);
213
+ const algorithm: KeyAlgorithm = 'rsa:2048';
111
214
  return {
112
- publicKey: formatAsPem(exPublic, 'PUBLIC KEY'),
113
- privateKey: formatAsPem(exPrivate, 'PRIVATE KEY'),
215
+ publicKey: wrapPublicKey(keyPair.publicKey, algorithm),
216
+ privateKey: wrapPrivateKey(keyPair.privateKey, algorithm),
114
217
  };
115
218
  }
116
219
 
117
220
  /**
118
- * Encrypt using a public key
119
- * @param payload Payload to encrypt
120
- * @param publicKey PEM formatted public key
221
+ * Encrypt using a public key (RSA-OAEP).
222
+ * Accepts Binary or SymmetricKey for key wrapping.
223
+ * @param payload Payload to encrypt (Binary) or symmetric key to wrap (SymmetricKey)
224
+ * @param publicKey Opaque public key
121
225
  * @return Encrypted payload
122
226
  */
123
- export async function encryptWithPublicKey(payload: Binary, publicKey: string): Promise<Binary> {
124
- console.assert(typeof payload === 'object');
125
- console.assert(typeof publicKey === 'string');
126
-
127
- const algoDomString = rsaOaepSha1();
227
+ export async function encryptWithPublicKey(
228
+ payload: Binary | SymmetricKey,
229
+ publicKey: PublicKey
230
+ ): Promise<Binary> {
231
+ let payloadBuffer: BufferSource;
128
232
 
129
- // Web Crypto APIs don't work with PEM formatted strings
130
- publicKey = removePemFormatting(publicKey);
233
+ // Handle SymmetricKey unwrapping
234
+ if ('_brand' in payload && payload._brand === 'SymmetricKey') {
235
+ // Pass Uint8Array directly — Web Crypto respects byteOffset/byteLength on typed array views.
236
+ payloadBuffer = unwrapSymmetricKey(payload);
237
+ } else {
238
+ // Binary payload
239
+ payloadBuffer = (payload as Binary).asArrayBuffer();
240
+ }
131
241
 
132
- const keyBuffer = base64Decode(publicKey);
133
- const cryptoKey = await crypto.subtle.importKey('spki', keyBuffer, algoDomString, false, [
134
- 'encrypt',
135
- ]);
136
- const result = await crypto.subtle.encrypt(
137
- { name: 'RSA-OAEP' },
138
- cryptoKey,
139
- payload.asArrayBuffer()
140
- );
242
+ const cryptoKey = unwrapKey(publicKey);
243
+ const result = await crypto.subtle.encrypt({ name: 'RSA-OAEP' }, cryptoKey, payloadBuffer);
141
244
  return Binary.fromArrayBuffer(result);
142
245
  }
143
246
 
144
- /**
145
- * Generate a 16-byte initialization vector
146
- */
147
- export async function generateInitializationVector(length?: number): Promise<string> {
148
- return randomBytesAsHex(length || 16);
149
- }
150
-
151
247
  export async function randomBytes(byteLength: number): Promise<Uint8Array> {
152
248
  const r = new Uint8Array(byteLength);
153
249
  crypto.getRandomValues(r);
@@ -174,26 +270,19 @@ export async function randomBytesAsHex(length: number): Promise<string> {
174
270
  /**
175
271
  * Decrypt a public-key encrypted payload with a private key
176
272
  * @param encryptedPayload Payload to decrypt
177
- * @param privateKey PEM formatted private keynpmv
273
+ * @param privateKey Opaque private key
178
274
  * @return Decrypted payload
179
275
  */
180
276
  export async function decryptWithPrivateKey(
181
277
  encryptedPayload: Binary,
182
- privateKey: string
278
+ privateKey: PrivateKey
183
279
  ): Promise<Binary> {
184
280
  console.assert(typeof encryptedPayload === 'object', 'encryptedPayload must be object');
185
- console.assert(typeof privateKey === 'string', 'privateKey must be string');
186
-
187
- const algoDomString = rsaOaepSha1();
188
281
 
189
- // Web Crypto APIs don't work with PEM formatted strings
190
- const keyDataString = removePemFormatting(privateKey);
191
- const keyData = base64Decode(keyDataString);
192
-
193
- const key = await crypto.subtle.importKey('pkcs8', keyData, algoDomString, false, ['decrypt']);
282
+ const cryptoKey = unwrapKey(privateKey);
194
283
  const payload = await crypto.subtle.decrypt(
195
284
  { name: 'RSA-OAEP' },
196
- key,
285
+ cryptoKey,
197
286
  encryptedPayload.asArrayBuffer()
198
287
  );
199
288
  const bufferView = new Uint8Array(payload);
@@ -203,14 +292,14 @@ export async function decryptWithPrivateKey(
203
292
  /**
204
293
  * Decrypt content synchronously
205
294
  * @param payload The payload to decrypt
206
- * @param key The encryption key
295
+ * @param key The symmetric encryption key (opaque)
207
296
  * @param iv The initialization vector
208
297
  * @param algorithm The algorithm to use for encryption
209
298
  * @param authTag The authentication tag for authenticated crypto.
210
299
  */
211
300
  export function decrypt(
212
301
  payload: Binary,
213
- key: Binary,
302
+ key: SymmetricKey,
214
303
  iv: Binary,
215
304
  algorithm?: AlgorithmUrn,
216
305
  authTag?: Binary
@@ -226,8 +315,8 @@ export function decrypt(
226
315
  * @param algorithm The algorithm to use for encryption
227
316
  */
228
317
  export function encrypt(
229
- payload: Binary,
230
- key: Binary,
318
+ payload: Binary | SymmetricKey,
319
+ key: SymmetricKey,
231
320
  iv: Binary,
232
321
  algorithm?: AlgorithmUrn
233
322
  ): Promise<EncryptResult> {
@@ -235,8 +324,8 @@ export function encrypt(
235
324
  }
236
325
 
237
326
  async function _doEncrypt(
238
- payload: Binary,
239
- key: Binary,
327
+ payload: Binary | SymmetricKey,
328
+ key: SymmetricKey,
240
329
  iv: Binary,
241
330
  algorithm?: AlgorithmUrn
242
331
  ): Promise<EncryptResult> {
@@ -244,10 +333,21 @@ async function _doEncrypt(
244
333
  console.assert(key != null);
245
334
  console.assert(iv != null);
246
335
 
247
- const payloadBuffer = payload.asArrayBuffer();
336
+ // Handle both Binary and SymmetricKey payloads
337
+ let payloadBuffer: BufferSource;
338
+ if ('_brand' in payload && payload._brand === 'SymmetricKey') {
339
+ // Pass Uint8Array directly — Web Crypto respects byteOffset/byteLength on typed array views.
340
+ payloadBuffer = unwrapSymmetricKey(payload);
341
+ } else {
342
+ // Binary payload
343
+ payloadBuffer = (payload as Binary).asArrayBuffer();
344
+ }
345
+
248
346
  const algoDomString = getSymmetricAlgoDomString(iv, algorithm);
249
347
 
250
- const importedKey = await _importKey(key, algoDomString);
348
+ // Unwrap symmetric key to get raw bytes
349
+ const keyBytes = unwrapSymmetricKey(key);
350
+ const importedKey = await _importKey(keyBytes, algoDomString);
251
351
  const encrypted = await crypto.subtle.encrypt(algoDomString, importedKey, payloadBuffer);
252
352
  if (algoDomString.name === 'AES-GCM') {
253
353
  return {
@@ -262,7 +362,7 @@ async function _doEncrypt(
262
362
 
263
363
  async function _doDecrypt(
264
364
  payload: Binary,
265
- key: Binary,
365
+ key: SymmetricKey,
266
366
  iv: Binary,
267
367
  algorithm?: AlgorithmUrn,
268
368
  authTag?: Binary
@@ -284,7 +384,9 @@ async function _doDecrypt(
284
384
 
285
385
  const algoDomString = getSymmetricAlgoDomString(iv, algorithm);
286
386
 
287
- const importedKey = await _importKey(key, algoDomString);
387
+ // Unwrap symmetric key to get raw bytes
388
+ const keyBytes = unwrapSymmetricKey(key);
389
+ const importedKey = await _importKey(keyBytes, algoDomString);
288
390
  algoDomString.iv = iv.asArrayBuffer();
289
391
 
290
392
  const decrypted = await crypto.subtle
@@ -300,8 +402,8 @@ async function _doDecrypt(
300
402
  return { payload: Binary.fromArrayBuffer(decrypted) };
301
403
  }
302
404
 
303
- function _importKey(key: Binary, algorithm: AesCbcParams | AesGcmParams) {
304
- return crypto.subtle.importKey('raw', key.asArrayBuffer(), algorithm, true, METHODS);
405
+ function _importKey(keyBytes: Uint8Array, algorithm: AesCbcParams | AesGcmParams) {
406
+ return crypto.subtle.importKey('raw', keyBytes, algorithm, true, ENC_DEC_METHODS);
305
407
  }
306
408
 
307
409
  /**
@@ -331,34 +433,6 @@ function getSymmetricAlgoDomString(
331
433
  * @param content String content
332
434
  * @return Hex hash
333
435
  */
334
- export async function sha256(content: string): Promise<string> {
335
- const buffer = new TextEncoder().encode(content);
336
- const hashBuffer = await crypto.subtle.digest('SHA-256', buffer);
337
- return hexEncode(hashBuffer);
338
- }
339
-
340
- /**
341
- * Create an HMAC SHA256 hash
342
- * @param key Key string
343
- * @param content Content string
344
- * @return Hex hash
345
- */
346
- export async function hmac(key: string, content: string): Promise<string> {
347
- const contentBuffer = new TextEncoder().encode(content);
348
- const keyBuffer = hex2Ab(key);
349
- const cryptoKey = await crypto.subtle.importKey(
350
- 'raw',
351
- keyBuffer,
352
- {
353
- name: 'HMAC',
354
- hash: { name: 'SHA-256' },
355
- },
356
- true,
357
- ['sign', 'verify']
358
- );
359
- const hashBuffer = await crypto.subtle.sign('HMAC', cryptoKey, contentBuffer);
360
- return hexEncode(hashBuffer);
361
- }
362
436
 
363
437
  /**
364
438
  * Create an ArrayBuffer from a hex string.
@@ -376,19 +450,848 @@ export function hex2Ab(hex: string): ArrayBuffer {
376
450
  return buffer;
377
451
  }
378
452
 
453
+ /**
454
+ * Get the Web Crypto algorithm parameters for a signing algorithm.
455
+ */
456
+ function getSigningAlgorithmParams(algorithm: AsymmetricSigningAlgorithm): {
457
+ importParams: RsaHashedImportParams | EcKeyImportParams;
458
+ signParams: AlgorithmIdentifier | EcdsaParams;
459
+ } {
460
+ switch (algorithm) {
461
+ case 'RS256':
462
+ return {
463
+ importParams: { name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' },
464
+ signParams: 'RSASSA-PKCS1-v1_5',
465
+ };
466
+ case 'ES256':
467
+ return {
468
+ importParams: { name: 'ECDSA', namedCurve: 'P-256' },
469
+ signParams: { name: 'ECDSA', hash: 'SHA-256' } as EcdsaParams,
470
+ };
471
+ case 'ES384':
472
+ return {
473
+ importParams: { name: 'ECDSA', namedCurve: 'P-384' },
474
+ signParams: { name: 'ECDSA', hash: 'SHA-384' } as EcdsaParams,
475
+ };
476
+ case 'ES512':
477
+ return {
478
+ importParams: { name: 'ECDSA', namedCurve: 'P-521' },
479
+ signParams: { name: 'ECDSA', hash: 'SHA-512' } as EcdsaParams,
480
+ };
481
+ default:
482
+ throw new ConfigurationError(`Unsupported signing algorithm: ${algorithm}`);
483
+ }
484
+ }
485
+
486
+ /**
487
+ * Convert IEEE P1363 signature format (used by WebCrypto ECDSA) to DER format (used by JWT).
488
+ * RS256 signatures don't need conversion.
489
+ */
490
+ function ieeeP1363ToDer(signature: Uint8Array, algorithm: AsymmetricSigningAlgorithm): Uint8Array {
491
+ if (algorithm === 'RS256') {
492
+ return signature;
493
+ }
494
+
495
+ // IEEE P1363: r || s where each is padded to key size
496
+ const halfLen = signature.length / 2;
497
+ const r = signature.slice(0, halfLen);
498
+ const s = signature.slice(halfLen);
499
+
500
+ // Remove leading zeros but keep one if the high bit is set
501
+ const trimLeadingZeros = (arr: Uint8Array): Uint8Array => {
502
+ let i = 0;
503
+ while (i < arr.length - 1 && arr[i] === 0) i++;
504
+ return arr.slice(i);
505
+ };
506
+
507
+ let rTrimmed = trimLeadingZeros(r);
508
+ let sTrimmed = trimLeadingZeros(s);
509
+
510
+ // Add leading zero if high bit is set (to keep positive in DER)
511
+ if (rTrimmed[0] & 0x80) {
512
+ const padded = new Uint8Array(rTrimmed.length + 1);
513
+ padded.set(rTrimmed, 1);
514
+ rTrimmed = padded;
515
+ }
516
+ if (sTrimmed[0] & 0x80) {
517
+ const padded = new Uint8Array(sTrimmed.length + 1);
518
+ padded.set(sTrimmed, 1);
519
+ sTrimmed = padded;
520
+ }
521
+
522
+ // DER SEQUENCE: 0x30 [length] [r INTEGER] [s INTEGER]
523
+ // INTEGER: 0x02 [length] [value]
524
+ const rDer = new Uint8Array([0x02, rTrimmed.length, ...rTrimmed]);
525
+ const sDer = new Uint8Array([0x02, sTrimmed.length, ...sTrimmed]);
526
+
527
+ const seqLen = rDer.length + sDer.length;
528
+ // DER length: short-form for < 128, long-form (0x81 nn) for 128-255.
529
+ // ECDSA sequences never exceed 255 bytes for any supported curve.
530
+ const lenBytes = seqLen < 128 ? new Uint8Array([seqLen]) : new Uint8Array([0x81, seqLen]);
531
+ const result = new Uint8Array(1 + lenBytes.length + seqLen);
532
+ result[0] = 0x30;
533
+ result.set(lenBytes, 1);
534
+ result.set(rDer, 1 + lenBytes.length);
535
+ result.set(sDer, 1 + lenBytes.length + rDer.length);
536
+
537
+ return result;
538
+ }
539
+
540
+ /**
541
+ * Convert DER signature format (used by JWT) to IEEE P1363 format (used by WebCrypto ECDSA).
542
+ * RS256 signatures don't need conversion.
543
+ */
544
+ function derToIeeeP1363(signature: Uint8Array, algorithm: AsymmetricSigningAlgorithm): Uint8Array {
545
+ if (algorithm === 'RS256') {
546
+ return signature;
547
+ }
548
+
549
+ // Determine the expected component length based on algorithm
550
+ let componentLen: number;
551
+ switch (algorithm) {
552
+ case 'ES256':
553
+ componentLen = 32;
554
+ break;
555
+ case 'ES384':
556
+ componentLen = 48;
557
+ break;
558
+ case 'ES512':
559
+ componentLen = 66;
560
+ break;
561
+ default:
562
+ throw new ConfigurationError(`Unsupported algorithm for DER conversion: ${algorithm}`);
563
+ }
564
+
565
+ // Parse DER: SEQUENCE { INTEGER r, INTEGER s }
566
+ if (signature[0] !== 0x30) {
567
+ throw new ConfigurationError('Invalid DER signature: expected SEQUENCE');
568
+ }
569
+
570
+ // Skip SEQUENCE tag, then parse DER length (short- or long-form).
571
+ let offset = 1;
572
+ if (signature[offset] & 0x80) {
573
+ // Long-form: low 7 bits = number of subsequent length bytes.
574
+ const lenBytesCount = signature[offset] & 0x7f;
575
+ if (lenBytesCount === 0 || lenBytesCount > 4) {
576
+ throw new ConfigurationError('Invalid DER signature: invalid long-form length');
577
+ }
578
+ offset += 1 + lenBytesCount;
579
+ if (offset > signature.length) {
580
+ throw new ConfigurationError('Invalid DER signature: length bytes exceed signature length');
581
+ }
582
+ } else {
583
+ // Short-form: single length byte.
584
+ offset += 1;
585
+ }
586
+
587
+ // Parse r INTEGER
588
+ if (signature[offset] !== 0x02) {
589
+ throw new ConfigurationError('Invalid DER signature: expected INTEGER for r');
590
+ }
591
+ const rLen = signature[offset + 1];
592
+ offset += 2;
593
+ let r = signature.slice(offset, offset + rLen);
594
+ offset += rLen;
595
+
596
+ // Parse s INTEGER
597
+ if (signature[offset] !== 0x02) {
598
+ throw new ConfigurationError('Invalid DER signature: expected INTEGER for s');
599
+ }
600
+ const sLen = signature[offset + 1];
601
+ offset += 2;
602
+ let s = signature.slice(offset, offset + sLen);
603
+
604
+ // Remove leading zero padding if present
605
+ if (r[0] === 0 && r.length > componentLen) {
606
+ r = r.slice(1);
607
+ }
608
+ if (s[0] === 0 && s.length > componentLen) {
609
+ s = s.slice(1);
610
+ }
611
+
612
+ // Pad to component length
613
+ const result = new Uint8Array(componentLen * 2);
614
+ result.set(r, componentLen - r.length);
615
+ result.set(s, componentLen * 2 - s.length);
616
+
617
+ return result;
618
+ }
619
+
620
+ /**
621
+ * Sign data with an asymmetric private key.
622
+ */
623
+ export async function sign(
624
+ data: Uint8Array,
625
+ privateKey: PrivateKey,
626
+ algorithm: AsymmetricSigningAlgorithm
627
+ ): Promise<Uint8Array> {
628
+ const { signParams } = getSigningAlgorithmParams(algorithm);
629
+
630
+ // Unwrap the internal CryptoKey
631
+ const key = unwrapKey(privateKey);
632
+
633
+ // Sign the data
634
+ const signature = await crypto.subtle.sign(signParams, key, data);
635
+
636
+ // Convert from IEEE P1363 to DER for EC algorithms
637
+ return ieeeP1363ToDer(new Uint8Array(signature), algorithm);
638
+ }
639
+
640
+ /**
641
+ * Verify signature with an asymmetric public key.
642
+ */
643
+ export async function verify(
644
+ data: Uint8Array,
645
+ signature: Uint8Array,
646
+ publicKey: PublicKey,
647
+ algorithm: AsymmetricSigningAlgorithm
648
+ ): Promise<boolean> {
649
+ const { signParams } = getSigningAlgorithmParams(algorithm);
650
+
651
+ // Unwrap the internal CryptoKey
652
+ const key = unwrapKey(publicKey);
653
+
654
+ // Convert from DER to IEEE P1363 for EC algorithms
655
+ const ieeeSignature = derToIeeeP1363(signature, algorithm);
656
+
657
+ // Verify the signature
658
+ return crypto.subtle.verify(signParams, key, ieeeSignature, data);
659
+ }
660
+
661
+ /**
662
+ * Compute hash digest.
663
+ */
664
+ export async function digest(algorithm: HashAlgorithm, data: Uint8Array): Promise<Uint8Array> {
665
+ // Validate algorithm and map to Web Crypto name
666
+ const validAlgorithms: HashAlgorithm[] = ['SHA-256', 'SHA-384', 'SHA-512'];
667
+ if (!validAlgorithms.includes(algorithm)) {
668
+ throw new ConfigurationError(`Unsupported hash algorithm: ${algorithm}`);
669
+ }
670
+
671
+ const hashBuffer = await crypto.subtle.digest(algorithm, data);
672
+ return new Uint8Array(hashBuffer);
673
+ }
674
+
675
+ /**
676
+ * Extract PEM public key from X.509 certificate or return PEM key as-is.
677
+ *
678
+ * @param certOrPem - A PEM-encoded X.509 certificate or public key
679
+ * @param jwaAlgorithm - JWA algorithm hint for certificate parsing (RS256, RS512, ES256, ES384, ES512).
680
+ * If not provided for a certificate, will attempt to auto-detect from OIDs.
681
+ */
682
+ export async function extractPublicKeyPem(
683
+ certOrPem: string,
684
+ jwaAlgorithm?: string
685
+ ): Promise<string> {
686
+ // If it's a certificate, extract the public key
687
+ if (certOrPem.includes('-----BEGIN CERTIFICATE-----')) {
688
+ let alg = jwaAlgorithm;
689
+ if (!alg) {
690
+ // Auto-detect algorithm from certificate OIDs
691
+ const certBody = certOrPem.replace(/-----(BEGIN|END) CERTIFICATE-----|\s/g, '');
692
+ const certBytes = base64Decode(certBody);
693
+ const hex = hexEncode(certBytes);
694
+ alg = toJwsAlg(hex);
695
+ }
696
+ const cert = await importX509(certOrPem, alg, { extractable: true });
697
+ return exportSPKI(cert);
698
+ }
699
+
700
+ // If it's already a PEM public key, return as-is
701
+ if (certOrPem.includes('-----BEGIN PUBLIC KEY-----')) {
702
+ return certOrPem;
703
+ }
704
+
705
+ throw new ConfigurationError('Input must be a PEM-encoded certificate or public key');
706
+ }
707
+
708
+ /**
709
+ * Map ECCurve to Web Crypto named curve.
710
+ */
711
+ function curveToNamedCurve(curve: ECCurve): string {
712
+ switch (curve) {
713
+ case 'P-256':
714
+ return 'P-256';
715
+ case 'P-384':
716
+ return 'P-384';
717
+ case 'P-521':
718
+ return 'P-521';
719
+ default:
720
+ throw new ConfigurationError(`Unsupported curve: ${curve}`);
721
+ }
722
+ }
723
+
724
+ /**
725
+ * Generate an EC key pair for ECDH key agreement.
726
+ */
727
+ export async function generateECKeyPair(curve: ECCurve = 'P-256'): Promise<KeyPair> {
728
+ const namedCurve = curveToNamedCurve(curve);
729
+
730
+ // Generate key pair for ECDH key agreement
731
+ const keyPair = await crypto.subtle.generateKey({ name: 'ECDH', namedCurve }, true, [
732
+ 'deriveBits',
733
+ ]);
734
+
735
+ // Map to KeyAlgorithm literal type
736
+ let algorithm: KeyAlgorithm;
737
+ switch (namedCurve) {
738
+ case 'P-256':
739
+ algorithm = 'ec:secp256r1';
740
+ break;
741
+ case 'P-384':
742
+ algorithm = 'ec:secp384r1';
743
+ break;
744
+ case 'P-521':
745
+ algorithm = 'ec:secp521r1';
746
+ break;
747
+ default:
748
+ throw new ConfigurationError(`Unsupported curve: ${namedCurve}`);
749
+ }
750
+
751
+ return {
752
+ publicKey: wrapPublicKey(keyPair.publicKey, algorithm),
753
+ privateKey: wrapPrivateKey(keyPair.privateKey, algorithm),
754
+ };
755
+ }
756
+
757
+ /**
758
+ * Supported EC curves.
759
+ */
760
+ const SUPPORTED_EC_CURVES = ['P-256', 'P-384', 'P-521'] as const;
761
+ type SupportedEcCurve = (typeof SUPPORTED_EC_CURVES)[number];
762
+
763
+ /**
764
+ * Decode base64url string and return byte length.
765
+ * Uses the existing base64 decoder which handles both standard and URL-safe encoding.
766
+ */
767
+ function base64urlByteLength(base64url: string): number {
768
+ // Add padding if needed (base64url omits padding)
769
+ const padding = (4 - (base64url.length % 4)) % 4;
770
+ const padded = base64url + '='.repeat(padding);
771
+ return base64Decode(padded).byteLength;
772
+ }
773
+
774
+ /**
775
+ * Extract EC curve from a public key by parsing ASN.1 OIDs.
776
+ * Reuses the existing guessCurveName function that checks for curve OIDs.
777
+ */
778
+ function extractEcCurveFromPublicKey(keyData: ArrayBuffer): SupportedEcCurve {
779
+ // Convert to hex for OID parsing
780
+ const hexKey = hexEncode(keyData);
781
+
782
+ // Use existing OID parser (returns 'P-256', 'P-384', or 'P-521')
783
+ const curveName = guessCurveName(hexKey);
784
+
785
+ return curveName as SupportedEcCurve;
786
+ }
787
+
788
+ /**
789
+ * Perform ECDH key agreement followed by HKDF key derivation.
790
+ * Returns opaque symmetric key for symmetric encryption.
791
+ */
792
+ export async function deriveKeyFromECDH(
793
+ privateKey: PrivateKey,
794
+ publicKey: PublicKey,
795
+ hkdfParams: HkdfParams
796
+ ): Promise<SymmetricKey> {
797
+ // Unwrap the internal CryptoKeys
798
+ const privateKeyCrypto = unwrapKey(privateKey);
799
+ const publicKeyCrypto = unwrapKey(publicKey);
800
+
801
+ // Get curve from key metadata
802
+ const curve = publicKey.curve;
803
+ if (!curve) {
804
+ throw new ConfigurationError('EC curve not found on public key');
805
+ }
806
+
807
+ // Determine bits based on curve
808
+ const curveBits: Record<ECCurve, number> = {
809
+ 'P-256': 256,
810
+ 'P-384': 384,
811
+ 'P-521': 528, // P-521 derives 528 bits (66 bytes)
812
+ };
813
+ const bits = curveBits[curve];
814
+
815
+ // Perform ECDH to get shared secret
816
+ const sharedSecret = await crypto.subtle.deriveBits(
817
+ { name: 'ECDH', public: publicKeyCrypto },
818
+ privateKeyCrypto,
819
+ bits
820
+ );
821
+
822
+ // Import shared secret as HKDF key material
823
+ const hkdfKey = await crypto.subtle.importKey('raw', sharedSecret, 'HKDF', false, ['deriveKey']);
824
+
825
+ // Derive the final key using HKDF
826
+ const keyLength = hkdfParams.keyLength ?? 256;
827
+ const derivedKey = await crypto.subtle.deriveKey(
828
+ {
829
+ name: 'HKDF',
830
+ hash: hkdfParams.hash,
831
+ salt: hkdfParams.salt,
832
+ info: hkdfParams.info ?? new Uint8Array(0),
833
+ },
834
+ hkdfKey,
835
+ { name: 'AES-GCM', length: keyLength },
836
+ true,
837
+ ['encrypt', 'decrypt']
838
+ );
839
+
840
+ // Export the derived key as raw bytes and wrap as SymmetricKey
841
+ const keyBytes = await crypto.subtle.exportKey('raw', derivedKey);
842
+ return wrapSymmetricKey(new Uint8Array(keyBytes));
843
+ }
844
+
845
+ /**
846
+ * Compute HMAC-SHA256 of data with a symmetric key.
847
+ */
848
+ export async function hmac(data: Uint8Array, key: SymmetricKey): Promise<Uint8Array> {
849
+ // Unwrap symmetric key to get raw bytes
850
+ const keyBytes = unwrapSymmetricKey(key);
851
+ const cryptoKey = await crypto.subtle.importKey(
852
+ 'raw',
853
+ keyBytes,
854
+ { name: 'HMAC', hash: 'SHA-256' },
855
+ false,
856
+ ['sign']
857
+ );
858
+
859
+ const signature = await crypto.subtle.sign('HMAC', cryptoKey, data);
860
+ return new Uint8Array(signature);
861
+ }
862
+
863
+ /**
864
+ * Verify HMAC-SHA256. Standalone utility — not part of CryptoService interface.
865
+ */
866
+ export async function verifyHmac(
867
+ data: Uint8Array,
868
+ signature: Uint8Array,
869
+ key: SymmetricKey
870
+ ): Promise<boolean> {
871
+ const keyBytes = unwrapSymmetricKey(key);
872
+ const cryptoKey = await crypto.subtle.importKey(
873
+ 'raw',
874
+ keyBytes,
875
+ { name: 'HMAC', hash: 'SHA-256' },
876
+ false,
877
+ ['verify']
878
+ );
879
+ return crypto.subtle.verify('HMAC', cryptoKey, signature, data);
880
+ }
881
+
882
+ /**
883
+ * Extract RSA modulus bit length by importing key and exporting as JWK.
884
+ * Uses Web Crypto's built-in ASN.1 parsing for robustness.
885
+ */
886
+ async function extractRsaModulusBitLength(keyData: ArrayBuffer): Promise<number> {
887
+ const key = await crypto.subtle.importKey(
888
+ 'spki',
889
+ keyData,
890
+ { name: 'RSA-OAEP', hash: 'SHA-256' },
891
+ true, // extractable
892
+ ['encrypt']
893
+ );
894
+ const jwk = await crypto.subtle.exportKey('jwk', key);
895
+ if (!jwk.n) {
896
+ throw new ConfigurationError('Invalid RSA key: missing modulus');
897
+ }
898
+ // JWK 'n' is base64url-encoded modulus
899
+ // Decode and count bytes, multiply by 8 for bits
900
+ return base64urlByteLength(jwk.n) * 8;
901
+ }
902
+
903
+ /**
904
+ * Import and validate a PEM public key, returning algorithm info.
905
+ * Uses JWK export for robust key parameter detection.
906
+ */
907
+ export async function parsePublicKeyPem(pem: string): Promise<PublicKeyInfo> {
908
+ // First extract public key if it's a certificate
909
+ let publicKeyPem = pem;
910
+ if (pem.includes('-----BEGIN CERTIFICATE-----')) {
911
+ publicKeyPem = await extractPublicKeyPem(pem);
912
+ }
913
+
914
+ if (!publicKeyPem.includes('-----BEGIN PUBLIC KEY-----')) {
915
+ throw new ConfigurationError('Input must be a PEM-encoded public key or certificate');
916
+ }
917
+
918
+ const keyData = base64Decode(removePemFormatting(publicKeyPem));
919
+
920
+ // Try RSA first - use JWK export to get modulus size
921
+ try {
922
+ const modulusBits = await extractRsaModulusBitLength(keyData);
923
+ let algorithm: PublicKeyInfo['algorithm'];
924
+ if (modulusBits < MIN_ASYMMETRIC_KEY_SIZE_BITS) {
925
+ throw new ConfigurationError(
926
+ `RSA key size ${modulusBits} bits is below the minimum of ${MIN_ASYMMETRIC_KEY_SIZE_BITS} bits`
927
+ );
928
+ } else if (modulusBits <= 2048) {
929
+ algorithm = 'rsa:2048';
930
+ } else if (modulusBits <= 4096) {
931
+ algorithm = 'rsa:4096';
932
+ } else {
933
+ throw new ConfigurationError(`Unsupported RSA key size: ${modulusBits} bits`);
934
+ }
935
+ return { algorithm, pem: publicKeyPem };
936
+ } catch (e) {
937
+ // If it's our own ConfigurationError, rethrow
938
+ if (e instanceof ConfigurationError) {
939
+ throw e;
940
+ }
941
+ // Not an RSA key, try EC next
942
+ }
943
+
944
+ // Try EC - parse curve from OID
945
+ try {
946
+ const detectedCurve = extractEcCurveFromPublicKey(keyData);
947
+ const curveMap = {
948
+ 'P-256': 'ec:secp256r1',
949
+ 'P-384': 'ec:secp384r1',
950
+ 'P-521': 'ec:secp521r1',
951
+ } as const;
952
+ return { algorithm: curveMap[detectedCurve], pem: publicKeyPem };
953
+ } catch {
954
+ // Not a valid EC key
955
+ }
956
+
957
+ throw new ConfigurationError('Unable to determine public key algorithm - unsupported key type');
958
+ }
959
+
960
+ /**
961
+ * Convert a JWK (JSON Web Key) to PEM format.
962
+ */
963
+ export async function jwkToPublicKeyPem(jwk: JsonWebKey): Promise<string> {
964
+ let key: CryptoKey;
965
+
966
+ if (jwk.kty === 'RSA') {
967
+ // RSA key
968
+ key = await crypto.subtle.importKey('jwk', jwk, { name: 'RSA-OAEP', hash: 'SHA-256' }, true, [
969
+ 'encrypt',
970
+ ]);
971
+ } else if (jwk.kty === 'EC') {
972
+ // EC key
973
+ const crv = jwk.crv;
974
+ if (!crv || !['P-256', 'P-384', 'P-521'].includes(crv)) {
975
+ throw new ConfigurationError(`Unsupported EC curve: ${crv}`);
976
+ }
977
+ key = await crypto.subtle.importKey('jwk', jwk, { name: 'ECDH', namedCurve: crv }, true, []);
978
+ } else {
979
+ throw new ConfigurationError(`Unsupported JWK key type: ${jwk.kty}`);
980
+ }
981
+
982
+ const spkiBuffer = await crypto.subtle.exportKey('spki', key);
983
+ return formatAsPem(spkiBuffer, 'PUBLIC KEY');
984
+ }
985
+
986
+ /**
987
+ * Convert a PEM public key to JWK format.
988
+ * Returns only public key components (no private key data).
989
+ */
990
+ export async function publicKeyPemToJwk(publicKeyPem: string): Promise<JsonWebKey> {
991
+ const keyDataBase64 = removePemFormatting(publicKeyPem);
992
+ const keyBuffer = base64Decode(keyDataBase64);
993
+ const hex = hexEncode(keyBuffer);
994
+
995
+ // Detect key type using OID
996
+ const algorithmName = guessAlgorithmName(hex);
997
+
998
+ if (algorithmName === 'ECDH' || algorithmName === 'ECDSA') {
999
+ // EC key - detect curve from OID
1000
+ const namedCurve = guessCurveName(hex);
1001
+ const key = await crypto.subtle.importKey(
1002
+ 'spki',
1003
+ keyBuffer,
1004
+ { name: 'ECDSA', namedCurve },
1005
+ true,
1006
+ ['verify']
1007
+ );
1008
+ const jwk = await crypto.subtle.exportKey('jwk', key);
1009
+ // Return only public key components
1010
+ const { kty, crv, x, y } = jwk;
1011
+ return { kty, crv, x, y };
1012
+ } else {
1013
+ // RSA key
1014
+ const key = await crypto.subtle.importKey(
1015
+ 'spki',
1016
+ keyBuffer,
1017
+ { name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' },
1018
+ true,
1019
+ ['verify']
1020
+ );
1021
+ const jwk = await crypto.subtle.exportKey('jwk', key);
1022
+ // Return only public key components
1023
+ const { kty, e, n } = jwk;
1024
+ return { kty, e, n };
1025
+ }
1026
+ }
1027
+
1028
+ // ============================================================
1029
+ // Key Import Functions (PEM → Opaque)
1030
+ // ============================================================
1031
+
1032
+ /**
1033
+ * Import a PEM public key as an opaque key.
1034
+ */
1035
+ export async function importPublicKey(pem: string, options: KeyOptions): Promise<PublicKey> {
1036
+ const { usage = 'encrypt', extractable = true, algorithmHint } = options;
1037
+
1038
+ // Detect algorithm from PEM; also normalises certificates → plain SPKI PEM.
1039
+ const keyInfo = await parsePublicKeyPem(pem);
1040
+ const algorithm = algorithmHint || keyInfo.algorithm;
1041
+
1042
+ // Use keyInfo.pem (normalised SPKI) not the original pem, which may be a certificate.
1043
+ // Passing raw X.509 DER bytes to crypto.subtle.importKey('spki') would throw DataError.
1044
+ const keyData = removePemFormatting(keyInfo.pem);
1045
+ const keyBuffer = base64Decode(keyData);
1046
+
1047
+ // Determine Web Crypto algorithm and usages based on key type and usage
1048
+ let cryptoAlgorithm: RsaHashedImportParams | EcKeyImportParams;
1049
+ let keyUsages: KeyUsage[];
1050
+
1051
+ if (algorithm.startsWith('rsa:')) {
1052
+ if (usage === 'encrypt') {
1053
+ cryptoAlgorithm = rsaOaepSha1();
1054
+ keyUsages = ['encrypt'];
1055
+ } else if (usage === 'sign') {
1056
+ cryptoAlgorithm = { name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' };
1057
+ keyUsages = ['verify'];
1058
+ } else {
1059
+ throw new ConfigurationError('RSA keys only support usage: encrypt or sign');
1060
+ }
1061
+ } else if (algorithm.startsWith('ec:')) {
1062
+ const curve = algorithm.split(':')[1];
1063
+ const namedCurve =
1064
+ curve === 'secp256r1'
1065
+ ? 'P-256'
1066
+ : curve === 'secp384r1'
1067
+ ? 'P-384'
1068
+ : curve === 'secp521r1'
1069
+ ? 'P-521'
1070
+ : (() => {
1071
+ throw new ConfigurationError(`Unsupported EC curve: ${curve}`);
1072
+ })();
1073
+
1074
+ if (usage === 'derive') {
1075
+ cryptoAlgorithm = { name: 'ECDH', namedCurve };
1076
+ keyUsages = [];
1077
+ } else if (usage === 'sign') {
1078
+ cryptoAlgorithm = { name: 'ECDSA', namedCurve };
1079
+ keyUsages = ['verify'];
1080
+ } else {
1081
+ throw new ConfigurationError('EC keys only support usage: derive or sign');
1082
+ }
1083
+ } else {
1084
+ throw new ConfigurationError(`Unsupported algorithm: ${algorithm}`);
1085
+ }
1086
+
1087
+ // Import as CryptoKey
1088
+ const cryptoKey = await crypto.subtle.importKey(
1089
+ 'spki',
1090
+ keyBuffer,
1091
+ cryptoAlgorithm,
1092
+ extractable,
1093
+ keyUsages
1094
+ );
1095
+
1096
+ return wrapPublicKey(cryptoKey, algorithm);
1097
+ }
1098
+
1099
+ /**
1100
+ * Import a PEM private key as an opaque key.
1101
+ */
1102
+ export async function importPrivateKey(pem: string, options: KeyOptions): Promise<PrivateKey> {
1103
+ const { usage = 'encrypt', extractable = true, algorithmHint } = options;
1104
+
1105
+ // Detect algorithm from PEM structure (similar to public key detection)
1106
+ // For now, use algorithmHint if provided, otherwise detect from key structure
1107
+ let algorithm: KeyAlgorithm;
1108
+
1109
+ const keyData = removePemFormatting(pem);
1110
+ const keyBuffer = base64Decode(keyData);
1111
+
1112
+ if (algorithmHint) {
1113
+ algorithm = algorithmHint;
1114
+ } else {
1115
+ // PKCS#8 PrivateKeyInfo embeds the same AlgorithmIdentifier OIDs as SPKI,
1116
+ // so guessAlgorithmName / guessCurveName work on private key bytes too.
1117
+ const hex = hexEncode(keyBuffer);
1118
+ const algorithmName = guessAlgorithmName(hex); // throws on unrecognised OID
1119
+ if (algorithmName === 'ECDH' || algorithmName === 'ECDSA') {
1120
+ const namedCurve = guessCurveName(hex);
1121
+ const curveMap: Record<string, KeyAlgorithm> = {
1122
+ 'P-256': 'ec:secp256r1',
1123
+ 'P-384': 'ec:secp384r1',
1124
+ 'P-521': 'ec:secp521r1',
1125
+ };
1126
+ const mapped = curveMap[namedCurve];
1127
+ if (!mapped)
1128
+ throw new ConfigurationError(`Unsupported EC curve in private key: ${namedCurve}`);
1129
+ algorithm = mapped;
1130
+ } else {
1131
+ // RSA — determine key size by importing and reading modulus length from JWK
1132
+ const tempKey = await crypto.subtle.importKey(
1133
+ 'pkcs8',
1134
+ keyBuffer,
1135
+ { name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' },
1136
+ true,
1137
+ ['sign']
1138
+ );
1139
+ const jwk = await crypto.subtle.exportKey('jwk', tempKey);
1140
+ if (!jwk.n) {
1141
+ throw new ConfigurationError('Invalid RSA private key: missing modulus');
1142
+ }
1143
+ const modulusBits = base64urlByteLength(jwk.n) * 8;
1144
+ if (modulusBits < MIN_ASYMMETRIC_KEY_SIZE_BITS) {
1145
+ throw new ConfigurationError(
1146
+ `RSA key size ${modulusBits} bits is below the minimum of ${MIN_ASYMMETRIC_KEY_SIZE_BITS} bits`
1147
+ );
1148
+ }
1149
+ algorithm = modulusBits <= 2048 ? 'rsa:2048' : 'rsa:4096';
1150
+ }
1151
+ }
1152
+
1153
+ // Determine Web Crypto algorithm and usages
1154
+ let cryptoAlgorithm: RsaHashedImportParams | EcKeyImportParams;
1155
+ let keyUsages: KeyUsage[];
1156
+
1157
+ if (algorithm.startsWith('rsa:')) {
1158
+ if (usage === 'encrypt') {
1159
+ cryptoAlgorithm = rsaOaepSha1();
1160
+ keyUsages = ['decrypt'];
1161
+ } else if (usage === 'sign') {
1162
+ cryptoAlgorithm = { name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' };
1163
+ keyUsages = ['sign'];
1164
+ } else {
1165
+ throw new ConfigurationError('RSA keys only support usage: encrypt or sign');
1166
+ }
1167
+ } else if (algorithm.startsWith('ec:')) {
1168
+ const curve = algorithm.split(':')[1];
1169
+ const namedCurve =
1170
+ curve === 'secp256r1'
1171
+ ? 'P-256'
1172
+ : curve === 'secp384r1'
1173
+ ? 'P-384'
1174
+ : curve === 'secp521r1'
1175
+ ? 'P-521'
1176
+ : (() => {
1177
+ throw new ConfigurationError(`Unsupported EC curve: ${curve}`);
1178
+ })();
1179
+
1180
+ if (usage === 'derive') {
1181
+ cryptoAlgorithm = { name: 'ECDH', namedCurve };
1182
+ keyUsages = ['deriveBits'];
1183
+ } else if (usage === 'sign') {
1184
+ cryptoAlgorithm = { name: 'ECDSA', namedCurve };
1185
+ keyUsages = ['sign'];
1186
+ } else {
1187
+ throw new ConfigurationError('EC keys only support usage: derive or sign');
1188
+ }
1189
+ } else {
1190
+ throw new ConfigurationError(`Unsupported algorithm: ${algorithm}`);
1191
+ }
1192
+
1193
+ // Import as CryptoKey
1194
+ const cryptoKey = await crypto.subtle.importKey(
1195
+ 'pkcs8',
1196
+ keyBuffer,
1197
+ cryptoAlgorithm,
1198
+ extractable,
1199
+ keyUsages
1200
+ );
1201
+
1202
+ return wrapPrivateKey(cryptoKey, algorithm);
1203
+ }
1204
+
1205
+ // ============================================================
1206
+ // Key Export Functions (Opaque → PEM/JWK)
1207
+ // ============================================================
1208
+
1209
+ /**
1210
+ * Export an opaque public key to PEM format.
1211
+ */
1212
+ export async function exportPublicKeyPem(key: PublicKey): Promise<string> {
1213
+ const cryptoKey = unwrapKey(key);
1214
+ const keyBuffer = await crypto.subtle.exportKey('spki', cryptoKey);
1215
+ return formatAsPem(keyBuffer, 'PUBLIC KEY');
1216
+ }
1217
+
1218
+ /**
1219
+ * Export an opaque private key to PEM format.
1220
+ * ONLY USE FOR TESTING/DEVELOPMENT. Private keys should NOT be exportable in secure environments.
1221
+ */
1222
+ export async function exportPrivateKeyPem(key: PrivateKey): Promise<string> {
1223
+ const cryptoKey = unwrapKey(key);
1224
+ const keyBuffer = await crypto.subtle.exportKey('pkcs8', cryptoKey);
1225
+ return formatAsPem(keyBuffer, 'PRIVATE KEY');
1226
+ }
1227
+
1228
+ /**
1229
+ * Export an opaque public key to JWK format.
1230
+ */
1231
+ export async function exportPublicKeyJwk(key: PublicKey): Promise<JsonWebKey> {
1232
+ const cryptoKey = unwrapKey(key);
1233
+ return await crypto.subtle.exportKey('jwk', cryptoKey);
1234
+ }
1235
+
1236
+ /**
1237
+ * Import raw key bytes as an opaque symmetric key.
1238
+ * Used for external keys (e.g., unwrapped from KAS).
1239
+ */
1240
+ export async function importSymmetricKey(keyBytes: Uint8Array): Promise<SymmetricKey> {
1241
+ return wrapSymmetricKey(keyBytes);
1242
+ }
1243
+
1244
+ /**
1245
+ * Split a symmetric key into N shares using XOR secret sharing.
1246
+ * Key bytes are extracted internally for splitting.
1247
+ * HSM implementations cannot extract bytes and should throw ConfigurationError.
1248
+ */
1249
+ export async function splitSymmetricKey(
1250
+ key: SymmetricKey,
1251
+ numShares: number
1252
+ ): Promise<SymmetricKey[]> {
1253
+ const keyBytes = unwrapSymmetricKey(key);
1254
+ const splits = await keySplit(keyBytes, numShares, DefaultCryptoService);
1255
+ return splits.map(wrapSymmetricKey);
1256
+ }
1257
+
1258
+ /**
1259
+ * Merge symmetric key shares back into the original key using XOR.
1260
+ * Key bytes are extracted internally for merging.
1261
+ */
1262
+ export async function mergeSymmetricKeys(shares: SymmetricKey[]): Promise<SymmetricKey> {
1263
+ const splitBytes = shares.map(unwrapSymmetricKey);
1264
+ const merged = keyMerge(splitBytes);
1265
+ return wrapSymmetricKey(merged);
1266
+ }
1267
+
379
1268
  export const DefaultCryptoService: CryptoService = {
380
1269
  name,
381
1270
  method,
382
- cryptoToPemPair,
383
1271
  decrypt,
384
1272
  decryptWithPrivateKey,
1273
+ deriveKeyFromECDH,
1274
+ digest,
385
1275
  encrypt,
386
1276
  encryptWithPublicKey,
387
- generateInitializationVector,
1277
+ exportPublicKeyJwk,
1278
+ exportPrivateKeyPem,
1279
+ exportPublicKeyPem,
1280
+ extractPublicKeyPem,
1281
+ generateECKeyPair,
388
1282
  generateKey,
389
1283
  generateKeyPair,
390
1284
  generateSigningKeyPair,
391
- hmac,
1285
+ importPrivateKey,
1286
+ importPublicKey,
1287
+ importSymmetricKey,
1288
+ jwkToPublicKeyPem,
1289
+ mergeSymmetricKeys,
1290
+ parsePublicKeyPem,
392
1291
  randomBytes,
393
- sha256,
1292
+ hmac,
1293
+ verifyHmac,
1294
+ sign,
1295
+ splitSymmetricKey,
1296
+ verify,
394
1297
  };