@enbox/crypto 0.0.1

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 (283) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +708 -0
  3. package/dist/browser.js +64 -0
  4. package/dist/browser.js.map +7 -0
  5. package/dist/browser.mjs +64 -0
  6. package/dist/browser.mjs.map +7 -0
  7. package/dist/cjs/algorithms/aes-ctr.js +188 -0
  8. package/dist/cjs/algorithms/aes-ctr.js.map +1 -0
  9. package/dist/cjs/algorithms/aes-gcm.js +196 -0
  10. package/dist/cjs/algorithms/aes-gcm.js.map +1 -0
  11. package/dist/cjs/algorithms/crypto-algorithm.js +13 -0
  12. package/dist/cjs/algorithms/crypto-algorithm.js.map +1 -0
  13. package/dist/cjs/algorithms/ecdsa.js +352 -0
  14. package/dist/cjs/algorithms/ecdsa.js.map +1 -0
  15. package/dist/cjs/algorithms/eddsa.js +325 -0
  16. package/dist/cjs/algorithms/eddsa.js.map +1 -0
  17. package/dist/cjs/algorithms/sha-2.js +119 -0
  18. package/dist/cjs/algorithms/sha-2.js.map +1 -0
  19. package/dist/cjs/index.js +41 -0
  20. package/dist/cjs/index.js.map +1 -0
  21. package/dist/cjs/jose/jwe.js +3 -0
  22. package/dist/cjs/jose/jwe.js.map +1 -0
  23. package/dist/cjs/jose/jwk.js +278 -0
  24. package/dist/cjs/jose/jwk.js.map +1 -0
  25. package/dist/cjs/jose/jws.js +3 -0
  26. package/dist/cjs/jose/jws.js.map +1 -0
  27. package/dist/cjs/jose/jwt.js +3 -0
  28. package/dist/cjs/jose/jwt.js.map +1 -0
  29. package/dist/cjs/jose/utils.js +60 -0
  30. package/dist/cjs/jose/utils.js.map +1 -0
  31. package/dist/cjs/local-key-manager.js +521 -0
  32. package/dist/cjs/local-key-manager.js.map +1 -0
  33. package/dist/cjs/package.json +1 -0
  34. package/dist/cjs/primitives/aes-ctr.js +398 -0
  35. package/dist/cjs/primitives/aes-ctr.js.map +1 -0
  36. package/dist/cjs/primitives/aes-gcm.js +425 -0
  37. package/dist/cjs/primitives/aes-gcm.js.map +1 -0
  38. package/dist/cjs/primitives/concat-kdf.js +215 -0
  39. package/dist/cjs/primitives/concat-kdf.js.map +1 -0
  40. package/dist/cjs/primitives/ed25519.js +651 -0
  41. package/dist/cjs/primitives/ed25519.js.map +1 -0
  42. package/dist/cjs/primitives/pbkdf2.js +120 -0
  43. package/dist/cjs/primitives/pbkdf2.js.map +1 -0
  44. package/dist/cjs/primitives/secp256k1.js +958 -0
  45. package/dist/cjs/primitives/secp256k1.js.map +1 -0
  46. package/dist/cjs/primitives/secp256r1.js +959 -0
  47. package/dist/cjs/primitives/secp256r1.js.map +1 -0
  48. package/dist/cjs/primitives/sha256.js +93 -0
  49. package/dist/cjs/primitives/sha256.js.map +1 -0
  50. package/dist/cjs/primitives/x25519.js +498 -0
  51. package/dist/cjs/primitives/x25519.js.map +1 -0
  52. package/dist/cjs/primitives/xchacha20-poly1305.js +340 -0
  53. package/dist/cjs/primitives/xchacha20-poly1305.js.map +1 -0
  54. package/dist/cjs/primitives/xchacha20.js +316 -0
  55. package/dist/cjs/primitives/xchacha20.js.map +1 -0
  56. package/dist/cjs/types/cipher.js +3 -0
  57. package/dist/cjs/types/cipher.js.map +1 -0
  58. package/dist/cjs/types/crypto-api.js +3 -0
  59. package/dist/cjs/types/crypto-api.js.map +1 -0
  60. package/dist/cjs/types/hasher.js +3 -0
  61. package/dist/cjs/types/hasher.js.map +1 -0
  62. package/dist/cjs/types/identifier.js +3 -0
  63. package/dist/cjs/types/identifier.js.map +1 -0
  64. package/dist/cjs/types/key-compressor.js +3 -0
  65. package/dist/cjs/types/key-compressor.js.map +1 -0
  66. package/dist/cjs/types/key-converter.js +3 -0
  67. package/dist/cjs/types/key-converter.js.map +1 -0
  68. package/dist/cjs/types/key-deriver.js +3 -0
  69. package/dist/cjs/types/key-deriver.js.map +1 -0
  70. package/dist/cjs/types/key-generator.js +3 -0
  71. package/dist/cjs/types/key-generator.js.map +1 -0
  72. package/dist/cjs/types/key-io.js +3 -0
  73. package/dist/cjs/types/key-io.js.map +1 -0
  74. package/dist/cjs/types/key-wrapper.js +3 -0
  75. package/dist/cjs/types/key-wrapper.js.map +1 -0
  76. package/dist/cjs/types/params-direct.js +3 -0
  77. package/dist/cjs/types/params-direct.js.map +1 -0
  78. package/dist/cjs/types/params-enclosed.js +3 -0
  79. package/dist/cjs/types/params-enclosed.js.map +1 -0
  80. package/dist/cjs/types/params-kms.js +3 -0
  81. package/dist/cjs/types/params-kms.js.map +1 -0
  82. package/dist/cjs/types/signer.js +3 -0
  83. package/dist/cjs/types/signer.js.map +1 -0
  84. package/dist/cjs/utils.js +173 -0
  85. package/dist/cjs/utils.js.map +1 -0
  86. package/dist/esm/algorithms/aes-ctr.js +124 -0
  87. package/dist/esm/algorithms/aes-ctr.js.map +1 -0
  88. package/dist/esm/algorithms/aes-gcm.js +132 -0
  89. package/dist/esm/algorithms/aes-gcm.js.map +1 -0
  90. package/dist/esm/algorithms/crypto-algorithm.js +6 -0
  91. package/dist/esm/algorithms/crypto-algorithm.js.map +1 -0
  92. package/dist/esm/algorithms/ecdsa.js +237 -0
  93. package/dist/esm/algorithms/ecdsa.js.map +1 -0
  94. package/dist/esm/algorithms/eddsa.js +213 -0
  95. package/dist/esm/algorithms/eddsa.js.map +1 -0
  96. package/dist/esm/algorithms/sha-2.js +57 -0
  97. package/dist/esm/algorithms/sha-2.js.map +1 -0
  98. package/dist/esm/index.js +25 -0
  99. package/dist/esm/index.js.map +1 -0
  100. package/dist/esm/jose/jwe.js +2 -0
  101. package/dist/esm/jose/jwe.js.map +1 -0
  102. package/dist/esm/jose/jwk.js +241 -0
  103. package/dist/esm/jose/jwk.js.map +1 -0
  104. package/dist/esm/jose/jws.js +2 -0
  105. package/dist/esm/jose/jws.js.map +1 -0
  106. package/dist/esm/jose/jwt.js +2 -0
  107. package/dist/esm/jose/jwt.js.map +1 -0
  108. package/dist/esm/jose/utils.js +34 -0
  109. package/dist/esm/jose/utils.js.map +1 -0
  110. package/dist/esm/local-key-manager.js +417 -0
  111. package/dist/esm/local-key-manager.js.map +1 -0
  112. package/dist/esm/primitives/aes-ctr.js +327 -0
  113. package/dist/esm/primitives/aes-ctr.js.map +1 -0
  114. package/dist/esm/primitives/aes-gcm.js +347 -0
  115. package/dist/esm/primitives/aes-gcm.js.map +1 -0
  116. package/dist/esm/primitives/concat-kdf.js +185 -0
  117. package/dist/esm/primitives/concat-kdf.js.map +1 -0
  118. package/dist/esm/primitives/ed25519.js +521 -0
  119. package/dist/esm/primitives/ed25519.js.map +1 -0
  120. package/dist/esm/primitives/pbkdf2.js +78 -0
  121. package/dist/esm/primitives/pbkdf2.js.map +1 -0
  122. package/dist/esm/primitives/secp256k1.js +805 -0
  123. package/dist/esm/primitives/secp256k1.js.map +1 -0
  124. package/dist/esm/primitives/secp256r1.js +806 -0
  125. package/dist/esm/primitives/secp256r1.js.map +1 -0
  126. package/dist/esm/primitives/sha256.js +55 -0
  127. package/dist/esm/primitives/sha256.js.map +1 -0
  128. package/dist/esm/primitives/x25519.js +392 -0
  129. package/dist/esm/primitives/x25519.js.map +1 -0
  130. package/dist/esm/primitives/xchacha20-poly1305.js +270 -0
  131. package/dist/esm/primitives/xchacha20-poly1305.js.map +1 -0
  132. package/dist/esm/primitives/xchacha20.js +246 -0
  133. package/dist/esm/primitives/xchacha20.js.map +1 -0
  134. package/dist/esm/types/cipher.js +2 -0
  135. package/dist/esm/types/cipher.js.map +1 -0
  136. package/dist/esm/types/crypto-api.js +2 -0
  137. package/dist/esm/types/crypto-api.js.map +1 -0
  138. package/dist/esm/types/hasher.js +2 -0
  139. package/dist/esm/types/hasher.js.map +1 -0
  140. package/dist/esm/types/identifier.js +2 -0
  141. package/dist/esm/types/identifier.js.map +1 -0
  142. package/dist/esm/types/key-compressor.js +2 -0
  143. package/dist/esm/types/key-compressor.js.map +1 -0
  144. package/dist/esm/types/key-converter.js +2 -0
  145. package/dist/esm/types/key-converter.js.map +1 -0
  146. package/dist/esm/types/key-deriver.js +2 -0
  147. package/dist/esm/types/key-deriver.js.map +1 -0
  148. package/dist/esm/types/key-generator.js +2 -0
  149. package/dist/esm/types/key-generator.js.map +1 -0
  150. package/dist/esm/types/key-io.js +2 -0
  151. package/dist/esm/types/key-io.js.map +1 -0
  152. package/dist/esm/types/key-wrapper.js +2 -0
  153. package/dist/esm/types/key-wrapper.js.map +1 -0
  154. package/dist/esm/types/params-direct.js +2 -0
  155. package/dist/esm/types/params-direct.js.map +1 -0
  156. package/dist/esm/types/params-enclosed.js +2 -0
  157. package/dist/esm/types/params-enclosed.js.map +1 -0
  158. package/dist/esm/types/params-kms.js +2 -0
  159. package/dist/esm/types/params-kms.js.map +1 -0
  160. package/dist/esm/types/signer.js +2 -0
  161. package/dist/esm/types/signer.js.map +1 -0
  162. package/dist/esm/utils.js +165 -0
  163. package/dist/esm/utils.js.map +1 -0
  164. package/dist/types/algorithms/aes-ctr.d.ts +121 -0
  165. package/dist/types/algorithms/aes-ctr.d.ts.map +1 -0
  166. package/dist/types/algorithms/aes-gcm.d.ts +152 -0
  167. package/dist/types/algorithms/aes-gcm.d.ts.map +1 -0
  168. package/dist/types/algorithms/crypto-algorithm.d.ts +6 -0
  169. package/dist/types/algorithms/crypto-algorithm.d.ts.map +1 -0
  170. package/dist/types/algorithms/ecdsa.d.ts +154 -0
  171. package/dist/types/algorithms/ecdsa.d.ts.map +1 -0
  172. package/dist/types/algorithms/eddsa.d.ts +151 -0
  173. package/dist/types/algorithms/eddsa.d.ts.map +1 -0
  174. package/dist/types/algorithms/sha-2.d.ts +51 -0
  175. package/dist/types/algorithms/sha-2.d.ts.map +1 -0
  176. package/dist/types/index.d.ts +39 -0
  177. package/dist/types/index.d.ts.map +1 -0
  178. package/dist/types/jose/jwe.d.ts +135 -0
  179. package/dist/types/jose/jwe.d.ts.map +1 -0
  180. package/dist/types/jose/jwk.d.ts +439 -0
  181. package/dist/types/jose/jwk.d.ts.map +1 -0
  182. package/dist/types/jose/jws.d.ts +67 -0
  183. package/dist/types/jose/jws.d.ts.map +1 -0
  184. package/dist/types/jose/jwt.d.ts +139 -0
  185. package/dist/types/jose/jwt.d.ts.map +1 -0
  186. package/dist/types/jose/utils.d.ts +14 -0
  187. package/dist/types/jose/utils.d.ts.map +1 -0
  188. package/dist/types/local-key-manager.d.ts +307 -0
  189. package/dist/types/local-key-manager.d.ts.map +1 -0
  190. package/dist/types/primitives/aes-ctr.d.ts +219 -0
  191. package/dist/types/primitives/aes-ctr.d.ts.map +1 -0
  192. package/dist/types/primitives/aes-gcm.d.ts +245 -0
  193. package/dist/types/primitives/aes-gcm.d.ts.map +1 -0
  194. package/dist/types/primitives/concat-kdf.d.ts +160 -0
  195. package/dist/types/primitives/concat-kdf.d.ts.map +1 -0
  196. package/dist/types/primitives/ed25519.d.ts +359 -0
  197. package/dist/types/primitives/ed25519.d.ts.map +1 -0
  198. package/dist/types/primitives/pbkdf2.d.ts +94 -0
  199. package/dist/types/primitives/pbkdf2.d.ts.map +1 -0
  200. package/dist/types/primitives/secp256k1.d.ts +598 -0
  201. package/dist/types/primitives/secp256k1.d.ts.map +1 -0
  202. package/dist/types/primitives/secp256r1.d.ts +599 -0
  203. package/dist/types/primitives/secp256r1.d.ts.map +1 -0
  204. package/dist/types/primitives/sha256.d.ts +42 -0
  205. package/dist/types/primitives/sha256.d.ts.map +1 -0
  206. package/dist/types/primitives/x25519.d.ts +283 -0
  207. package/dist/types/primitives/x25519.d.ts.map +1 -0
  208. package/dist/types/primitives/xchacha20-poly1305.d.ts +210 -0
  209. package/dist/types/primitives/xchacha20-poly1305.d.ts.map +1 -0
  210. package/dist/types/primitives/xchacha20.d.ts +186 -0
  211. package/dist/types/primitives/xchacha20.d.ts.map +1 -0
  212. package/dist/types/types/cipher.d.ts +49 -0
  213. package/dist/types/types/cipher.d.ts.map +1 -0
  214. package/dist/types/types/crypto-api.d.ts +40 -0
  215. package/dist/types/types/crypto-api.d.ts.map +1 -0
  216. package/dist/types/types/hasher.d.ts +33 -0
  217. package/dist/types/types/hasher.d.ts.map +1 -0
  218. package/dist/types/types/identifier.d.ts +16 -0
  219. package/dist/types/types/identifier.d.ts.map +1 -0
  220. package/dist/types/types/key-compressor.d.ts +28 -0
  221. package/dist/types/types/key-compressor.d.ts.map +1 -0
  222. package/dist/types/types/key-converter.d.ts +57 -0
  223. package/dist/types/types/key-converter.d.ts.map +1 -0
  224. package/dist/types/types/key-deriver.d.ts +39 -0
  225. package/dist/types/types/key-deriver.d.ts.map +1 -0
  226. package/dist/types/types/key-generator.d.ts +105 -0
  227. package/dist/types/types/key-generator.d.ts.map +1 -0
  228. package/dist/types/types/key-io.d.ts +37 -0
  229. package/dist/types/types/key-io.d.ts.map +1 -0
  230. package/dist/types/types/key-wrapper.d.ts +38 -0
  231. package/dist/types/types/key-wrapper.d.ts.map +1 -0
  232. package/dist/types/types/params-direct.d.ts +90 -0
  233. package/dist/types/types/params-direct.d.ts.map +1 -0
  234. package/dist/types/types/params-enclosed.d.ts +47 -0
  235. package/dist/types/types/params-enclosed.d.ts.map +1 -0
  236. package/dist/types/types/params-kms.d.ts +131 -0
  237. package/dist/types/types/params-kms.d.ts.map +1 -0
  238. package/dist/types/types/signer.d.ts +46 -0
  239. package/dist/types/types/signer.d.ts.map +1 -0
  240. package/dist/types/utils.d.ts +112 -0
  241. package/dist/types/utils.d.ts.map +1 -0
  242. package/dist/utils.js +7 -0
  243. package/dist/utils.js.map +7 -0
  244. package/package.json +103 -0
  245. package/src/algorithms/aes-ctr.ts +156 -0
  246. package/src/algorithms/aes-gcm.ts +187 -0
  247. package/src/algorithms/crypto-algorithm.ts +4 -0
  248. package/src/algorithms/ecdsa.ts +269 -0
  249. package/src/algorithms/eddsa.ts +243 -0
  250. package/src/algorithms/sha-2.ts +65 -0
  251. package/src/index.ts +42 -0
  252. package/src/jose/jwe.ts +196 -0
  253. package/src/jose/jwk.ts +632 -0
  254. package/src/jose/jws.ts +95 -0
  255. package/src/jose/jwt.ts +147 -0
  256. package/src/jose/utils.ts +34 -0
  257. package/src/local-key-manager.ts +540 -0
  258. package/src/primitives/aes-ctr.ts +352 -0
  259. package/src/primitives/aes-gcm.ts +378 -0
  260. package/src/primitives/concat-kdf.ts +240 -0
  261. package/src/primitives/ed25519.ts +548 -0
  262. package/src/primitives/pbkdf2.ts +122 -0
  263. package/src/primitives/secp256k1.ts +848 -0
  264. package/src/primitives/secp256r1.ts +850 -0
  265. package/src/primitives/sha256.ts +47 -0
  266. package/src/primitives/x25519.ts +403 -0
  267. package/src/primitives/xchacha20-poly1305.ts +274 -0
  268. package/src/primitives/xchacha20.ts +247 -0
  269. package/src/types/cipher.ts +53 -0
  270. package/src/types/crypto-api.ts +56 -0
  271. package/src/types/hasher.ts +32 -0
  272. package/src/types/identifier.ts +16 -0
  273. package/src/types/key-compressor.ts +25 -0
  274. package/src/types/key-converter.ts +53 -0
  275. package/src/types/key-deriver.ts +43 -0
  276. package/src/types/key-generator.ts +119 -0
  277. package/src/types/key-io.ts +42 -0
  278. package/src/types/key-wrapper.ts +42 -0
  279. package/src/types/params-direct.ts +106 -0
  280. package/src/types/params-enclosed.ts +50 -0
  281. package/src/types/params-kms.ts +156 -0
  282. package/src/types/signer.ts +50 -0
  283. package/src/utils.ts +181 -0
@@ -0,0 +1,378 @@
1
+ import { Convert } from '@enbox/common';
2
+ import { getWebcryptoSubtle } from '@noble/ciphers/webcrypto';
3
+
4
+ import type { Jwk } from '../jose/jwk.js';
5
+
6
+ import { computeJwkThumbprint, isOctPrivateJwk } from '../jose/jwk.js';
7
+
8
+ /**
9
+ * Const defining the AES-GCM initialization vector (IV) length in bits.
10
+ *
11
+ * @remarks
12
+ * NIST Special Publication 800-38D, Section 5.2.1.1 states that the IV length:
13
+ * > For IVs, it is recommended that implementations restrict support to the length of 96 bits, to
14
+ * > promote interoperability, efficiency, and simplicity of design.
15
+ *
16
+ * This implementation does not support IV lengths that are different from the value defined by
17
+ * this constant.
18
+ *
19
+ * @see {@link https://doi.org/10.6028/NIST.SP.800-38D | NIST SP 800-38D}
20
+ */
21
+ const AES_GCM_IV_LENGTH = 96;
22
+
23
+ /**
24
+ * Constant defining the AES key length values in bits.
25
+ *
26
+ * @remarks
27
+ * NIST publication FIPS 197 states:
28
+ * > The AES algorithm is capable of using cryptographic keys of 128, 192, and 256 bits to encrypt
29
+ * > and decrypt data in blocks of 128 bits.
30
+ *
31
+ * This implementation does not support key lengths that are different from the three values
32
+ * defined by this constant.
33
+ *
34
+ * @see {@link https://doi.org/10.6028/NIST.FIPS.197-upd1 | NIST FIPS 197}
35
+ */
36
+ const AES_KEY_LENGTHS = [128, 192, 256] as const;
37
+
38
+ /**
39
+ * Constant defining the AES-GCM tag length values in bits.
40
+ *
41
+ * @remarks
42
+ * NIST Special Publication 800-38D, Section 5.2.1.2 states that the tag length:
43
+ * > may be any one of the following five values: 128, 120, 112, 104, or 96
44
+ *
45
+ * Although the NIST specification allows for tag lengths of 32 or 64 bits in certain applications,
46
+ * the use of shorter tag lengths can be problematic for GCM due to targeted forgery attacks. As a
47
+ * precaution, this implementation does not support tag lengths that are different from the five
48
+ * values defined by this constant. See Appendix C of the NIST SP 800-38D specification for
49
+ * additional guidance and details.
50
+ *
51
+ * @see {@link https://doi.org/10.6028/NIST.SP.800-38D | NIST SP 800-38D}
52
+ */
53
+ export const AES_GCM_TAG_LENGTHS = [96, 104, 112, 120, 128] as const;
54
+
55
+ /**
56
+ * The `AesGcm` class provides a comprehensive set of utilities for cryptographic operations
57
+ * using the Advanced Encryption Standard (AES) in Galois/Counter Mode (GCM). This class includes
58
+ * methods for key generation, encryption, decryption, and conversions between raw byte arrays
59
+ * and JSON Web Key (JWK) formats. It is designed to support AES-GCM, a symmetric key algorithm
60
+ * that is widely used for its efficiency, security, and provision of authenticated encryption.
61
+ *
62
+ * AES-GCM is particularly favored for scenarios that require both confidentiality and integrity
63
+ * of data. It integrates the counter mode of encryption with the Galois mode of authentication,
64
+ * offering high performance and parallel processing capabilities.
65
+ *
66
+ * Key Features:
67
+ * - Key Generation: Generate AES symmetric keys in JWK format.
68
+ * - Key Conversion: Transform keys between raw byte arrays and JWK formats.
69
+ * - Encryption: Encrypt data using AES-GCM with the provided symmetric key.
70
+ * - Decryption: Decrypt data encrypted with AES-GCM using the corresponding symmetric key.
71
+ *
72
+ * The methods in this class are asynchronous, returning Promises to accommodate various
73
+ * JavaScript environments.
74
+ *
75
+ * @example
76
+ * ```ts
77
+ * // Key Generation
78
+ * const length = 256; // Length of the key in bits (e.g., 128, 192, 256)
79
+ * const privateKey = await AesGcm.generateKey({ length });
80
+ *
81
+ * // Encryption
82
+ * const data = new TextEncoder().encode('Messsage');
83
+ * const iv = new Uint8Array(12); // 12-byte initialization vector
84
+ * const encryptedData = await AesGcm.encrypt({
85
+ * data,
86
+ * iv,
87
+ * key: privateKey
88
+ * });
89
+ *
90
+ * // Decryption
91
+ * const decryptedData = await AesGcm.decrypt({
92
+ * data: encryptedData,
93
+ * iv,
94
+ * key: privateKey
95
+ * });
96
+ *
97
+ * // Key Conversion
98
+ * const privateKeyBytes = await AesGcm.privateKeyToBytes({ privateKey });
99
+ * ```
100
+ */
101
+ export class AesGcm {
102
+ /**
103
+ * Converts a raw private key in bytes to its corresponding JSON Web Key (JWK) format.
104
+ *
105
+ * @remarks
106
+ * This method accepts a symmetric key represented as a byte array (Uint8Array) and
107
+ * converts it into a JWK object for use with AES-GCM (Advanced Encryption Standard -
108
+ * Galois/Counter Mode). The conversion process involves encoding the key into
109
+ * base64url format and setting the appropriate JWK parameters.
110
+ *
111
+ * The resulting JWK object includes the following properties:
112
+ * - `kty`: Key Type, set to 'oct' for Octet Sequence (representing a symmetric key).
113
+ * - `k`: The symmetric key, base64url-encoded.
114
+ * - `kid`: Key ID, generated based on the JWK thumbprint.
115
+ *
116
+ * @example
117
+ * ```ts
118
+ * const privateKeyBytes = new Uint8Array([...]); // Replace with actual symmetric key bytes
119
+ * const privateKey = await AesGcm.bytesToPrivateKey({ privateKeyBytes });
120
+ * ```
121
+ *
122
+ * @param params - The parameters for the symmetric key conversion.
123
+ * @param params.privateKeyBytes - The raw symmetric key as a Uint8Array.
124
+ *
125
+ * @returns A Promise that resolves to the symmetric key in JWK format.
126
+ */
127
+ public static async bytesToPrivateKey({ privateKeyBytes }: {
128
+ privateKeyBytes: Uint8Array;
129
+ }): Promise<Jwk> {
130
+ // Construct the private key in JWK format.
131
+ const privateKey: Jwk = {
132
+ k : Convert.uint8Array(privateKeyBytes).toBase64Url(),
133
+ kty : 'oct'
134
+ };
135
+
136
+ // Compute the JWK thumbprint and set as the key ID.
137
+ privateKey.kid = await computeJwkThumbprint({ jwk: privateKey });
138
+
139
+ return privateKey;
140
+ }
141
+
142
+ /**
143
+ * Decrypts the provided data using AES-GCM.
144
+ *
145
+ * @remarks
146
+ * This method performs AES-GCM decryption on the given encrypted data using the specified key.
147
+ * It requires an initialization vector (IV), the encrypted data along with the decryption key,
148
+ * and optionally, additional authenticated data (AAD). The method returns the decrypted data as a
149
+ * Uint8Array. The optional `tagLength` parameter specifies the size in bits of the authentication
150
+ * tag used when encrypting the data. If not specified, the default tag length of 128 bits is
151
+ * used.
152
+ *
153
+ * @example
154
+ * ```ts
155
+ * const encryptedData = new Uint8Array([...]); // Encrypted data
156
+ * const iv = new Uint8Array([...]); // Initialization vector used during encryption
157
+ * const additionalData = new Uint8Array([...]); // Optional additional authenticated data
158
+ * const key = { ... }; // A Jwk object representing the AES key
159
+ * const decryptedData = await AesGcm.decrypt({
160
+ * data: encryptedData,
161
+ * iv,
162
+ * additionalData,
163
+ * key,
164
+ * tagLength: 128 // Optional tag length in bits
165
+ * });
166
+ * ```
167
+ *
168
+ * @param params - The parameters for the decryption operation.
169
+ * @param params.key - The key to use for decryption, represented in JWK format.
170
+ * @param params.data - The encrypted data to decrypt, represented as a Uint8Array.
171
+ * @param params.iv - The initialization vector, represented as a Uint8Array.
172
+ * @param params.additionalData - Optional additional authenticated data. Optional.
173
+ * @param params.tagLength - The length of the authentication tag in bits. Optional.
174
+ *
175
+ * @returns A Promise that resolves to the decrypted data as a Uint8Array.
176
+ */
177
+ public static async decrypt({ key, data, iv, additionalData, tagLength }: {
178
+ key: Jwk;
179
+ data: Uint8Array;
180
+ iv: Uint8Array;
181
+ additionalData?: Uint8Array;
182
+ tagLength?: typeof AES_GCM_TAG_LENGTHS[number];
183
+ }): Promise<Uint8Array> {
184
+ // Validate the initialization vector length.
185
+ if (iv.byteLength !== AES_GCM_IV_LENGTH / 8) {
186
+ throw new TypeError(`The initialization vector must be ${AES_GCM_IV_LENGTH} bits in length`);
187
+ }
188
+
189
+ // Validate the tag length.
190
+ if (tagLength && !AES_GCM_TAG_LENGTHS.includes(tagLength as any)) {
191
+ throw new RangeError(`The tag length is invalid: Must be ${AES_GCM_TAG_LENGTHS.join(', ')} bits`);
192
+ }
193
+
194
+ // Get the Web Crypto API interface.
195
+ const webCrypto = getWebcryptoSubtle();
196
+
197
+ // Import the JWK into the Web Crypto API to use for the decrypt operation.
198
+ const webCryptoKey = await webCrypto.importKey('jwk', key, { name: 'AES-GCM' }, true, ['decrypt']);
199
+
200
+ // Note: Some browser implementations of the Web Crypto API throw an error if additionalData or
201
+ // tagLength are undefined, so only include them in the algorithm object if they are defined.
202
+ const algorithm = {
203
+ name: 'AES-GCM',
204
+ iv,
205
+ ...(tagLength && { tagLength }),
206
+ ...(additionalData && { additionalData})
207
+ };
208
+
209
+ // Decrypt the data.
210
+ const plaintextBuffer = await webCrypto.decrypt(algorithm, webCryptoKey, data);
211
+
212
+ // Convert from ArrayBuffer to Uint8Array.
213
+ const plaintext = new Uint8Array(plaintextBuffer);
214
+
215
+ return plaintext;
216
+ }
217
+
218
+ /**
219
+ * Encrypts the provided data using AES-GCM.
220
+ *
221
+ * @remarks
222
+ * This method performs AES-GCM encryption on the given data using the specified key.
223
+ * It requires an initialization vector (IV), the encrypted data along with the decryption key,
224
+ * and optionally, additional authenticated data (AAD). The method returns the encrypted data as a
225
+ * Uint8Array. The optional `tagLength` parameter specifies the size in bits of the authentication
226
+ * tag generated in the encryption operation and used for authentication in the corresponding
227
+ * decryption. If not specified, the default tag length of 128 bits is used.
228
+ *
229
+ * @example
230
+ * ```ts
231
+ * const data = new TextEncoder().encode('Messsage');
232
+ * const iv = new Uint8Array([...]); // Initialization vector
233
+ * const additionalData = new Uint8Array([...]); // Optional additional authenticated data
234
+ * const key = { ... }; // A Jwk object representing an AES key
235
+ * const encryptedData = await AesGcm.encrypt({
236
+ * data,
237
+ * iv,
238
+ * additionalData,
239
+ * key,
240
+ * tagLength: 128 // Optional tag length in bits
241
+ * });
242
+ * ```
243
+ *
244
+ * @param params - The parameters for the encryption operation.
245
+ * @param params.key - The key to use for encryption, represented in JWK format.
246
+ * @param params.data - The data to encrypt, represented as a Uint8Array.
247
+ * @param params.iv - The initialization vector, represented as a Uint8Array.
248
+ * @param params.additionalData - Optional additional authenticated data. Optional.
249
+ * @param params.tagLength - The length of the authentication tag in bits. Optional.
250
+ *
251
+ * @returns A Promise that resolves to the encrypted data as a Uint8Array.
252
+ */
253
+ public static async encrypt({ data, iv, key, additionalData, tagLength }: {
254
+ key: Jwk;
255
+ data: Uint8Array;
256
+ iv: Uint8Array;
257
+ additionalData?: Uint8Array;
258
+ tagLength?: typeof AES_GCM_TAG_LENGTHS[number];
259
+ }): Promise<Uint8Array> {
260
+ // Validate the initialization vector length.
261
+ if (iv.byteLength !== AES_GCM_IV_LENGTH / 8) {
262
+ throw new TypeError(`The initialization vector must be ${AES_GCM_IV_LENGTH} bits in length`);
263
+ }
264
+
265
+ // Validate the tag length.
266
+ if (tagLength && !AES_GCM_TAG_LENGTHS.includes(tagLength as any)) {
267
+ throw new RangeError(`The tag length is invalid: Must be ${AES_GCM_TAG_LENGTHS.join(', ')} bits`);
268
+ }
269
+
270
+ // Get the Web Crypto API interface.
271
+ const webCrypto = getWebcryptoSubtle();
272
+
273
+ // Import the JWK into the Web Crypto API to use for the encrypt operation.
274
+ const webCryptoKey = await webCrypto.importKey('jwk', key, { name: 'AES-GCM' }, true, ['encrypt']);
275
+
276
+ // Note: Some browser implementations of the Web Crypto API throw an error if additionalData or
277
+ // tagLength are undefined, so only include them in the algorithm object if they are defined.
278
+ const algorithm = {
279
+ name: 'AES-GCM',
280
+ iv,
281
+ ...(tagLength && { tagLength }),
282
+ ...(additionalData && { additionalData})
283
+ };
284
+
285
+ // Encrypt the data.
286
+ const ciphertextBuffer = await webCrypto.encrypt(algorithm, webCryptoKey, data);
287
+
288
+ // Convert from ArrayBuffer to Uint8Array.
289
+ const ciphertext = new Uint8Array(ciphertextBuffer);
290
+
291
+ return ciphertext;
292
+ }
293
+
294
+ /**
295
+ * Generates a symmetric key for AES in Galois/Counter Mode (GCM) in JSON Web Key (JWK) format.
296
+ *
297
+ * @remarks
298
+ * This method creates a new symmetric key of a specified length suitable for use with
299
+ * AES-GCM encryption. It leverages cryptographically secure random number generation
300
+ * to ensure the uniqueness and security of the key. The generated key adheres to the JWK
301
+ * format, facilitating compatibility with common cryptographic standards and ease of use
302
+ * in various cryptographic applications.
303
+ *
304
+ * The generated key includes these components:
305
+ * - `kty`: Key Type, set to 'oct' for Octet Sequence, indicating a symmetric key.
306
+ * - `k`: The symmetric key component, base64url-encoded.
307
+ * - `kid`: Key ID, generated based on the JWK thumbprint, providing a unique identifier.
308
+ *
309
+ * @example
310
+ * ```ts
311
+ * const length = 256; // Length of the key in bits (e.g., 128, 192, 256)
312
+ * const privateKey = await AesGcm.generateKey({ length });
313
+ * ```
314
+ *
315
+ * @param params - The parameters for the key generation.
316
+ * @param params.length - The length of the key in bits. Common lengths are 128, 192, and 256 bits.
317
+ *
318
+ * @returns A Promise that resolves to the generated symmetric key in JWK format.
319
+ */
320
+ public static async generateKey({ length }: {
321
+ length: typeof AES_KEY_LENGTHS[number];
322
+ }): Promise<Jwk> {
323
+ // Validate the key length.
324
+ if (!AES_KEY_LENGTHS.includes(length as any)) {
325
+ throw new RangeError(`The key length is invalid: Must be ${AES_KEY_LENGTHS.join(', ')} bits`);
326
+ }
327
+
328
+ // Get the Web Crypto API interface.
329
+ const webCrypto = getWebcryptoSubtle();
330
+
331
+ // Generate a random private key.
332
+ // See https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues#usage_notes for
333
+ // an explanation for why Web Crypto generateKey() is used instead of getRandomValues().
334
+ const webCryptoKey = await webCrypto.generateKey( { name: 'AES-GCM', length }, true, ['encrypt']);
335
+
336
+ // Export the private key in JWK format.
337
+ const { ext, key_ops, ...privateKey } = await webCrypto.exportKey('jwk', webCryptoKey);
338
+
339
+ // Compute the JWK thumbprint and set as the key ID.
340
+ privateKey.kid = await computeJwkThumbprint({ jwk: privateKey });
341
+
342
+ return privateKey;
343
+ }
344
+
345
+ /**
346
+ * Converts a private key from JSON Web Key (JWK) format to a raw byte array (Uint8Array).
347
+ *
348
+ * @remarks
349
+ * This method takes a symmetric key in JWK format and extracts its raw byte representation.
350
+ * It focuses on the 'k' parameter of the JWK, which represents the symmetric key component
351
+ * in base64url encoding. The method decodes this value into a byte array, providing
352
+ * the symmetric key in its raw binary form.
353
+ *
354
+ * @example
355
+ * ```ts
356
+ * const privateKey = { ... }; // A symmetric key in JWK format
357
+ * const privateKeyBytes = await AesGcm.privateKeyToBytes({ privateKey });
358
+ * ```
359
+ *
360
+ * @param params - The parameters for the symmetric key conversion.
361
+ * @param params.privateKey - The symmetric key in JWK format.
362
+ *
363
+ * @returns A Promise that resolves to the symmetric key as a Uint8Array.
364
+ */
365
+ public static async privateKeyToBytes({ privateKey }: {
366
+ privateKey: Jwk;
367
+ }): Promise<Uint8Array> {
368
+ // Verify the provided JWK represents a valid oct private key.
369
+ if (!isOctPrivateJwk(privateKey)) {
370
+ throw new Error(`AesGcm: The provided key is not a valid oct private key.`);
371
+ }
372
+
373
+ // Decode the provided private key to bytes.
374
+ const privateKeyBytes = Convert.base64Url(privateKey.k).toUint8Array();
375
+
376
+ return privateKeyBytes;
377
+ }
378
+ }
@@ -0,0 +1,240 @@
1
+ import { sha256 } from '@noble/hashes/sha256';
2
+ import { Convert, universalTypeOf } from '@enbox/common';
3
+ import { TypedArray, concatBytes } from '@noble/hashes/utils';
4
+
5
+ /**
6
+ * ConcatKDF FixedInfo Parameters.
7
+ *
8
+ * This implementation follows the recommended format for `FixedInfo` specified in section 5.8.2
9
+ * of the NIST.800-56A publication.
10
+ *
11
+ * @see {@link https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-56Ar3.pdf | NIST.800-56A}
12
+ * @see {@link https://datatracker.ietf.org/doc/html/rfc7518#section-4.6.2 | RFC 7518, Section 4.6.2}
13
+ */
14
+ export type ConcatKdfFixedInfo = {
15
+ /**
16
+ * The algorithm the derived secret keying material will be used with.
17
+ */
18
+ algorithmId: string;
19
+
20
+ /**
21
+ * Information related to party U (initiator) involved in the key agreement
22
+ * transaction. It could be a public key, identifier, or any other data.
23
+ */
24
+ partyUInfo: string | TypedArray;
25
+
26
+ /**
27
+ * Information related to party V (receiver) involved in the key
28
+ * agreement transaction. Similar to partyUInfo, it could be a
29
+ * public key, identifier, etc.
30
+ */
31
+ partyVInfo: string | TypedArray;
32
+
33
+ /**
34
+ * Optional field. It is usually used to ensure the uniqueness of the
35
+ * derived keying material when the input keying material is used in
36
+ * multiple key-derivation key-agreement transactions. It is usually
37
+ * a public value such as the keyDataLen.
38
+ */
39
+ suppPubInfo?: number;
40
+
41
+ /**
42
+ * Optional field. It is used when it is desired to secretively
43
+ * bind additional information into the derived keying material.
44
+ * It is a secret value agreed upon by the entities who are party
45
+ * to the key agreement.
46
+ */
47
+ suppPrivInfo?: string | TypedArray;
48
+ }
49
+
50
+ /**
51
+ * An implementation of the Concatenation Key Derivation Function (ConcatKDF)
52
+ * as specified in NIST.800-56A, a single-step key-derivation function (SSKDF).
53
+ * ConcatKDF produces a derived key from a secret key (like a shared secret
54
+ * from ECDH), and other optional public information. This implementation
55
+ * specifically uses SHA-256 as the pseudorandom function (PRF).
56
+ *
57
+ * Note: This implementation allows for only a single round / repetition using the function
58
+ * `K(1) = H(counter || Z || FixedInfo)`, where:
59
+ * - `K(1)` is the derived key material after one round
60
+ * - `H` is the SHA-256 hashing function
61
+ * - `counter` is a 32-bit, big-endian bit string counter set to 0x00000001
62
+ * - `Z` is the shared secret value obtained from a key agreement protocol
63
+ * - `FixedInfo` is a bit string used to ensure that the derived keying material is adequately
64
+ * "bound" to the key-agreement transaction.
65
+ *
66
+ * @example
67
+ * ```ts
68
+ * // Key Derivation
69
+ * const derivedKeyingMaterial = await ConcatKdf.deriveKey({
70
+ * sharedSecret: utils.randomBytes(32),
71
+ * keyDataLen: 128,
72
+ * fixedInfo: {
73
+ * algorithmId: "A128GCM",
74
+ * partyUInfo: "Alice",
75
+ * partyVInfo: "Bob",
76
+ * suppPubInfo: 128,
77
+ * },
78
+ * });
79
+ * ```
80
+ *
81
+ * Additional Information:
82
+ *
83
+ * `Z`, or "shared secret":
84
+ * The shared secret value obtained from a key agreement protocol, such as
85
+ * Diffie-Hellman, ECDH (Elliptic Curve Diffie-Hellman). Importantly, this
86
+ * shared secret is not directly used as the encryption or authentication
87
+ * key, but as an input to a key derivation function (KDF), such as Concat
88
+ * KDF, to generate the actual key. This adds an extra layer of security, as
89
+ * even if the shared secret gets compromised, the actual encryption or
90
+ * authentication key stays safe. This shared secret `Z` value is kept
91
+ * confidential between the two parties in the key agreement protocol.
92
+ *
93
+ * @see {@link https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-56Ar3.pdf | NIST.800-56A}
94
+ * @see {@link https://datatracker.ietf.org/doc/html/rfc7518#section-4.6.2 | RFC 7518, Section 4.6.2}
95
+ */
96
+ export class ConcatKdf {
97
+ /**
98
+ * Derives a key of a specified length from the input parameters.
99
+ *
100
+ * @example
101
+ * ```ts
102
+ * // Key Derivation
103
+ * const derivedKeyingMaterial = await ConcatKdf.deriveKey({
104
+ * sharedSecret: utils.randomBytes(32),
105
+ * keyDataLen: 128,
106
+ * fixedInfo: {
107
+ * algorithmId: "A128GCM",
108
+ * partyUInfo: "Alice",
109
+ * partyVInfo: "Bob",
110
+ * suppPubInfo: 128,
111
+ * },
112
+ * });
113
+ * ```
114
+ *
115
+ * @param params - Input parameters for key derivation.
116
+ * @param params.keyDataLen - The desired length of the derived key in bits.
117
+ * @param params.sharedSecret - The shared secret key to derive from.
118
+ * @param params.fixedInfo - Additional public information to use in key derivation.
119
+ * @returns The derived key as a Uint8Array.
120
+ *
121
+ * @throws {Error} If the `keyDataLen` would require multiple rounds.
122
+ */
123
+ public static async deriveKey({ keyDataLen, fixedInfo, sharedSecret }: {
124
+ keyDataLen: number;
125
+ fixedInfo: ConcatKdfFixedInfo;
126
+ sharedSecret: Uint8Array;
127
+ }): Promise<Uint8Array> {
128
+ // RFC 7518 Section 4.6.2 specifies using SHA-256 for ECDH key agreement:
129
+ // "Key derivation is performed using the Concat KDF, as defined in
130
+ // Section 5.8.1 of [NIST.800-56A], where the Digest Method is SHA-256."
131
+ // Reference: https://tools.ietf.org/html/rfc7518#section-4.6.2
132
+ const hashLen = 256;
133
+
134
+ // This implementation only supports single round Concat KDF.
135
+ const roundCount = Math.ceil(keyDataLen / hashLen);
136
+ if (roundCount !== 1) {
137
+ throw new Error(`Concat KDF with ${roundCount} rounds not supported.`);
138
+ }
139
+
140
+ // Initialize a 32-bit, big-endian bit string counter as 0x00000001.
141
+ const counter = new Uint8Array(4);
142
+ new DataView(counter.buffer).setUint32(0, roundCount);
143
+
144
+ // Compute the FixedInfo bit-string.
145
+ const fixedInfoBytes = ConcatKdf.computeFixedInfo(fixedInfo);
146
+
147
+ // Compute K(i) = H(counter || Z || FixedInfo)
148
+ // return concatBytes(counter, sharedSecretZ, fixedInfo);
149
+ const derivedKeyingMaterial = sha256(concatBytes(counter, sharedSecret, fixedInfoBytes));
150
+
151
+ // Return the bit string of derived keying material of length keyDataLen bits.
152
+ return derivedKeyingMaterial.slice(0, keyDataLen / 8);
153
+ }
154
+
155
+ /**
156
+ * Computes the `FixedInfo` parameter for Concat KDF, which binds the derived key material to the
157
+ * context of the key agreement transaction.
158
+ *
159
+ * @remarks
160
+ * This implementation follows the recommended format for `FixedInfo` specified in section
161
+ * 5.8.1.2.1 of the NIST.800-56A publication.
162
+ *
163
+ * `FixedInfo` is a bit string equal to the following concatenation:
164
+ * `AlgorithmID || PartyUInfo || PartyVInfo {|| SuppPubInfo }{|| SuppPrivInfo }`.
165
+ *
166
+ * `SuppPubInfo` is the key length in bits, big endian encoded as a 32-bit number. For example,
167
+ * 128 would be [0, 0, 0, 128] and 256 would be [0, 0, 1, 0].
168
+ *
169
+ * @param params - Input data to construct FixedInfo.
170
+ * @returns FixedInfo as a Uint8Array.
171
+ */
172
+ private static computeFixedInfo(params:
173
+ ConcatKdfFixedInfo
174
+ ): Uint8Array {
175
+ // Required sub-fields.
176
+ const algorithmId = ConcatKdf.toDataLenData({ data: params.algorithmId });
177
+ const partyUInfo = ConcatKdf.toDataLenData({ data: params.partyUInfo });
178
+ const partyVInfo = ConcatKdf.toDataLenData({ data: params.partyVInfo });
179
+ // Optional sub-fields.
180
+ const suppPubInfo = ConcatKdf.toDataLenData({ data: params.suppPubInfo, variableLength: false });
181
+ const suppPrivInfo = ConcatKdf.toDataLenData({ data: params.suppPrivInfo });
182
+
183
+ // Concatenate AlgorithmID || PartyUInfo || PartyVInfo || SuppPubInfo || SuppPrivInfo.
184
+ const fixedInfo = concatBytes(algorithmId, partyUInfo, partyVInfo, suppPubInfo, suppPrivInfo);
185
+
186
+ return fixedInfo;
187
+ }
188
+
189
+ /**
190
+ * Encodes input data as a length-prefixed byte string, or
191
+ * as a fixed-length bit string if specified.
192
+ *
193
+ * If variableLength = true, return the data in the form Datalen || Data,
194
+ * where Data is a variable-length string of zero or more (eight-bit)
195
+ * bytes, and Datalen is a fixed-length, big-endian counter that
196
+ * indicates the length (in bytes) of Data.
197
+ *
198
+ * If variableLength = false, return the data formatted as a
199
+ * fixed-length bit string.
200
+ *
201
+ * @param params - Input data and options for the conversion.
202
+ * @param params.data - The input data to encode. Must be a type convertible to Uint8Array by the Convert class.
203
+ * @param params.variableLength - Whether to output the data as variable length. Default is true.
204
+ *
205
+ * @returns The input data encoded as a Uint8Array.
206
+ *
207
+ * @throws {TypeError} If fixed-length data is not a number.
208
+ */
209
+ private static toDataLenData({ data, variableLength = true }: {
210
+ data: unknown;
211
+ variableLength?: boolean;
212
+ }): Uint8Array {
213
+ let encodedData: Uint8Array;
214
+ const dataType = universalTypeOf(data);
215
+
216
+ // Return an emtpy octet sequence if data is not specified.
217
+ if (dataType === 'Undefined') {
218
+ return new Uint8Array(0);
219
+ }
220
+
221
+ if (variableLength) {
222
+ const dataU8A = (dataType === 'Uint8Array')
223
+ ? data as Uint8Array
224
+ : new Convert(data, dataType).toUint8Array();
225
+ const bufferLength = dataU8A.length;
226
+ encodedData = new Uint8Array(4 + bufferLength);
227
+ new DataView(encodedData.buffer).setUint32(0, bufferLength);
228
+ encodedData.set(dataU8A, 4);
229
+
230
+ } else {
231
+ if (typeof data !== 'number') {
232
+ throw TypeError('Fixed length input must be a number.');
233
+ }
234
+ encodedData = new Uint8Array(4);
235
+ new DataView(encodedData.buffer).setUint32(0, data);
236
+ }
237
+
238
+ return encodedData;
239
+ }
240
+ }