@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,548 @@
1
+ import { Convert } from '@enbox/common';
2
+ import { ed25519, edwardsToMontgomeryPub, edwardsToMontgomeryPriv, x25519 } from '@noble/curves/ed25519';
3
+
4
+ import type { Jwk } from '../jose/jwk.js';
5
+ import type { ComputePublicKeyParams, GetPublicKeyParams, SignParams, VerifyParams } from '../types/params-direct.js';
6
+
7
+ import { computeJwkThumbprint, isOkpPrivateJwk, isOkpPublicJwk } from '../jose/jwk.js';
8
+
9
+ /**
10
+ * The `Ed25519` class provides a comprehensive suite of utilities for working with the Ed25519
11
+ * elliptic curve, widely used in modern cryptographic applications. This class includes methods for
12
+ * key generation, conversion, signing, verification, and public key derivation.
13
+ *
14
+ * The class supports conversions between raw byte formats and JSON Web Key (JWK) formats. It
15
+ * follows the guidelines and specifications outlined in RFC8032 for EdDSA (Edwards-curve Digital
16
+ * Signature Algorithm) operations.
17
+ *
18
+ * Key Features:
19
+ * - Key Generation: Generate Ed25519 private keys in JWK format.
20
+ * - Key Conversion: Transform keys between raw byte arrays and JWK formats.
21
+ * - Public Key Derivation: Derive public keys from private keys.
22
+ * - Signing and Verification: Sign data and verify signatures with Ed25519 keys.
23
+ * - Key Validation: Validate the mathematical correctness of Ed25519 keys.
24
+ *
25
+ * The methods in this class are asynchronous, returning Promises to accommodate various
26
+ * JavaScript environments, and use `Uint8Array` for binary data handling.
27
+ *
28
+ * @example
29
+ * ```ts
30
+ * // Key Generation
31
+ * const privateKey = await Ed25519.generateKey();
32
+ *
33
+ * // Public Key Derivation
34
+ * const publicKey = await Ed25519.computePublicKey({ key: privateKey });
35
+ * console.log(publicKey === await Ed25519.getPublicKey({ key: privateKey })); // Output: true
36
+ *
37
+ * // EdDSA Signing
38
+ * const signature = await Ed25519.sign({
39
+ * key: privateKey,
40
+ * data: new TextEncoder().encode('Message')
41
+ * });
42
+ *
43
+ * // EdDSA Signature Verification
44
+ * const isValid = await Ed25519.verify({
45
+ * key: publicKey,
46
+ * signature: signature,
47
+ * data: new TextEncoder().encode('Message')
48
+ * });
49
+ *
50
+ * // Key Conversion
51
+ * const privateKeyBytes = await Ed25519.privateKeyToBytes({ privateKey });
52
+ * const publicKeyBytes = await Ed25519.publicKeyToBytes({ publicKey });
53
+ *
54
+ * // Key Validation
55
+ * const isPublicKeyValid = await Ed25519.validatePublicKey({ publicKeyBytes });
56
+ * ```
57
+ */
58
+ export class Ed25519 {
59
+ /**
60
+ * Converts a raw private key in bytes to its corresponding JSON Web Key (JWK) format.
61
+ *
62
+ * @remarks
63
+ * This method accepts a private key as a byte array (Uint8Array) for the Curve25519 curve in
64
+ * Twisted Edwards form and transforms it into a JWK object. The process involves first deriving
65
+ * the public key from the private key, then encoding both the private and public keys into
66
+ * base64url format.
67
+ *
68
+ * The resulting JWK object includes the following properties:
69
+ * - `kty`: Key Type, set to 'OKP' for Octet Key Pair.
70
+ * - `crv`: Curve Name, set to 'Ed25519'.
71
+ * - `d`: The private key component, base64url-encoded.
72
+ * - `x`: The computed public key, base64url-encoded.
73
+ *
74
+ * @example
75
+ * ```ts
76
+ * const privateKeyBytes = new Uint8Array([...]); // Replace with actual private key bytes
77
+ * const privateKey = await Ed25519.bytesToPrivateKey({ privateKeyBytes });
78
+ * ```
79
+ *
80
+ * @param params - The parameters for the private key conversion.
81
+ * @param params.privateKeyBytes - The raw private key as a Uint8Array.
82
+ *
83
+ * @returns A Promise that resolves to the private key in JWK format.
84
+ */
85
+ public static async bytesToPrivateKey({ privateKeyBytes }: {
86
+ privateKeyBytes: Uint8Array;
87
+ }): Promise<Jwk> {
88
+ // Derive the public key from the private key.
89
+ const publicKeyBytes = ed25519.getPublicKey(privateKeyBytes);
90
+
91
+ // Construct the private key in JWK format.
92
+ const privateKey: Jwk = {
93
+ crv : 'Ed25519',
94
+ d : Convert.uint8Array(privateKeyBytes).toBase64Url(),
95
+ kty : 'OKP',
96
+ x : Convert.uint8Array(publicKeyBytes).toBase64Url(),
97
+ };
98
+
99
+ // Compute the JWK thumbprint and set as the key ID.
100
+ privateKey.kid = await computeJwkThumbprint({ jwk: privateKey });
101
+
102
+ return privateKey;
103
+ }
104
+
105
+ /**
106
+ * Converts a raw private key in bytes to its corresponding JSON Web Key (JWK) format.
107
+ *
108
+ * @remarks
109
+ * This method accepts a public key as a byte array (Uint8Array) for the Curve25519 curve in
110
+ * Twisted Edwards form and transforms it into a JWK object. The process involves encoding the
111
+ * public key bytes into base64url format.
112
+ *
113
+ * The resulting JWK object includes the following properties:
114
+ * - `kty`: Key Type, set to 'OKP' for Octet Key Pair.
115
+ * - `crv`: Curve Name, set to 'X25519'.
116
+ * - `x`: The public key, base64url-encoded.
117
+ *
118
+ * @example
119
+ * ```ts
120
+ * const publicKeyBytes = new Uint8Array([...]); // Replace with actual public key bytes
121
+ * const publicKey = await X25519.bytesToPublicKey({ publicKeyBytes });
122
+ * ```
123
+ *
124
+ * @param params - The parameters for the public key conversion.
125
+ * @param params.publicKeyBytes - The raw public key as a `Uint8Array`.
126
+ *
127
+ * @returns A Promise that resolves to the public key in JWK format.
128
+ */
129
+ public static async bytesToPublicKey({ publicKeyBytes }: {
130
+ publicKeyBytes: Uint8Array;
131
+ }): Promise<Jwk> {
132
+ // Construct the public key in JWK format.
133
+ const publicKey: Jwk = {
134
+ kty : 'OKP',
135
+ crv : 'Ed25519',
136
+ x : Convert.uint8Array(publicKeyBytes).toBase64Url(),
137
+ };
138
+
139
+ // Compute the JWK thumbprint and set as the key ID.
140
+ publicKey.kid = await computeJwkThumbprint({ jwk: publicKey });
141
+
142
+ return publicKey;
143
+ }
144
+
145
+ /**
146
+ * Derives the public key in JWK format from a given Ed25519 private key.
147
+ *
148
+ * @remarks
149
+ * This method takes a private key in JWK format and derives its corresponding public key,
150
+ * also in JWK format. The derivation process involves converting the private key to a
151
+ * raw byte array and then computing the corresponding public key on the Curve25519 curve in
152
+ * Twisted Edwards form. The public key is then encoded into base64url format to construct
153
+ * a JWK representation.
154
+ *
155
+ * @example
156
+ * ```ts
157
+ * const privateKey = { ... }; // A Jwk object representing an Ed25519 private key
158
+ * const publicKey = await Ed25519.computePublicKey({ key: privateKey });
159
+ * ```
160
+ *
161
+ * @param params - The parameters for the public key derivation.
162
+ * @param params.key - The private key in JWK format from which to derive the public key.
163
+ *
164
+ * @returns A Promise that resolves to the computed public key in JWK format.
165
+ */
166
+ public static async computePublicKey({ key }:
167
+ ComputePublicKeyParams
168
+ ): Promise<Jwk> {
169
+ // Convert the provided private key to a byte array.
170
+ const privateKeyBytes = await Ed25519.privateKeyToBytes({ privateKey: key });
171
+
172
+ // Derive the public key from the private key.
173
+ const publicKeyBytes = ed25519.getPublicKey(privateKeyBytes);
174
+
175
+ // Construct the public key in JWK format.
176
+ const publicKey: Jwk = {
177
+ kty : 'OKP',
178
+ crv : 'Ed25519',
179
+ x : Convert.uint8Array(publicKeyBytes).toBase64Url()
180
+ };
181
+
182
+ // Compute the JWK thumbprint and set as the key ID.
183
+ publicKey.kid = await computeJwkThumbprint({ jwk: publicKey });
184
+
185
+ return publicKey;
186
+ }
187
+
188
+ /**
189
+ * Converts an Ed25519 private key to its X25519 counterpart.
190
+ *
191
+ * @remarks
192
+ * This method enables the use of the same key pair for both digital signature (Ed25519)
193
+ * and key exchange (X25519) operations. It takes an Ed25519 private key and converts it
194
+ * to the corresponding X25519 format, facilitating interoperability between signing
195
+ * and encryption protocols.
196
+ *
197
+ * @example
198
+ * ```ts
199
+ * const ed25519PrivateKey = { ... }; // An Ed25519 private key in JWK format
200
+ * const x25519PrivateKey = await Ed25519.convertPrivateKeyToX25519({
201
+ * privateKey: ed25519PrivateKey
202
+ * });
203
+ * ```
204
+ *
205
+ * @param params - The parameters for the private key conversion.
206
+ * @param params.privateKey - The Ed25519 private key to convert, in JWK format.
207
+ *
208
+ * @returns A Promise that resolves to the X25519 private key in JWK format.
209
+ */
210
+ public static async convertPrivateKeyToX25519({ privateKey }: {
211
+ privateKey: Jwk;
212
+ }): Promise<Jwk> {
213
+ // Convert the provided Ed25519 private key to bytes.
214
+ const ed25519PrivateKeyBytes = await Ed25519.privateKeyToBytes({ privateKey });
215
+
216
+ // Convert the Ed25519 private key to an X25519 private key.
217
+ const x25519PrivateKeyBytes = edwardsToMontgomeryPriv(ed25519PrivateKeyBytes);
218
+
219
+ // Derive the X25519 public key from the X25519 private key.
220
+ const x25519PublicKeyBytes = x25519.getPublicKey(x25519PrivateKeyBytes);
221
+
222
+ // Construct the X25519 private key in JWK format.
223
+ const x25519PrivateKey: Jwk = {
224
+ kty : 'OKP',
225
+ crv : 'X25519',
226
+ d : Convert.uint8Array(x25519PrivateKeyBytes).toBase64Url(),
227
+ x : Convert.uint8Array(x25519PublicKeyBytes).toBase64Url(),
228
+ };
229
+
230
+ // Compute the JWK thumbprint and set as the key ID.
231
+ x25519PrivateKey.kid = await computeJwkThumbprint({ jwk: x25519PrivateKey });
232
+
233
+ return x25519PrivateKey;
234
+ }
235
+
236
+ /**
237
+ * Converts an Ed25519 public key to its X25519 counterpart.
238
+ *
239
+ * @remarks
240
+ * This method enables the use of the same key pair for both digital signature (Ed25519)
241
+ * and key exchange (X25519) operations. It takes an Ed25519 public key and converts it
242
+ * to the corresponding X25519 format, facilitating interoperability between signing
243
+ * and encryption protocols.
244
+ *
245
+ * @example
246
+ * ```ts
247
+ * const ed25519PublicKey = { ... }; // An Ed25519 public key in JWK format
248
+ * const x25519PublicKey = await Ed25519.convertPublicKeyToX25519({
249
+ * publicKey: ed25519PublicKey
250
+ * });
251
+ * ```
252
+ *
253
+ * @param params - The parameters for the public key conversion.
254
+ * @param params.publicKey - The Ed25519 public key to convert, in JWK format.
255
+ *
256
+ * @returns A Promise that resolves to the X25519 public key in JWK format.
257
+ */
258
+ public static async convertPublicKeyToX25519({ publicKey }: {
259
+ publicKey: Jwk;
260
+ }): Promise<Jwk> {
261
+ // Convert the provided private key to a byte array.
262
+ const ed25519PublicKeyBytes = await Ed25519.publicKeyToBytes({ publicKey });
263
+
264
+ // Verify Edwards public key is valid.
265
+ const isValid = await Ed25519.validatePublicKey({ publicKeyBytes: ed25519PublicKeyBytes });
266
+ if (!isValid) {
267
+ throw new Error('Ed25519: Invalid public key.');
268
+ }
269
+
270
+ // Convert the Ed25519 public key to an X25519 private key.
271
+ const x25519PublicKeyBytes = edwardsToMontgomeryPub(ed25519PublicKeyBytes);
272
+
273
+ // Construct the X25519 private key in JWK format.
274
+ const x25519PublicKey: Jwk = {
275
+ kty : 'OKP',
276
+ crv : 'X25519',
277
+ x : Convert.uint8Array(x25519PublicKeyBytes).toBase64Url(),
278
+ };
279
+
280
+ // Compute the JWK thumbprint and set as the key ID.
281
+ x25519PublicKey.kid = await computeJwkThumbprint({ jwk: x25519PublicKey });
282
+
283
+ return x25519PublicKey;
284
+ }
285
+
286
+ /**
287
+ * Generates an Ed25519 private key in JSON Web Key (JWK) format.
288
+ *
289
+ * @remarks
290
+ * This method creates a new private key suitable for use with the Curve25519 elliptic curve in
291
+ * Twisted Edwards form. The key generation process involves using cryptographically secure
292
+ * random number generation to ensure the uniqueness and security of the key. The resulting
293
+ * private key adheres to the JWK format making it compatible with common cryptographic
294
+ * standards and easy to use in various cryptographic processes.
295
+ *
296
+ * The generated private key in JWK format includes the following components:
297
+ * - `kty`: Key Type, set to 'OKP' for Octet Key Pair.
298
+ * - `crv`: Curve Name, set to 'Ed25519'.
299
+ * - `d`: The private key component, base64url-encoded.
300
+ * - `x`: The derived public key, base64url-encoded.
301
+ *
302
+ * @example
303
+ * ```ts
304
+ * const privateKey = await Ed25519.generateKey();
305
+ * ```
306
+ *
307
+ * @returns A Promise that resolves to the generated private key in JWK format.
308
+ */
309
+ public static async generateKey(): Promise<Jwk> {
310
+ // Generate a random private key.
311
+ const privateKeyBytes = ed25519.utils.randomPrivateKey();
312
+
313
+ // Convert private key from bytes to JWK format.
314
+ const privateKey = await Ed25519.bytesToPrivateKey({ privateKeyBytes });
315
+
316
+ // Compute the JWK thumbprint and set as the key ID.
317
+ privateKey.kid = await computeJwkThumbprint({ jwk: privateKey });
318
+
319
+ return privateKey;
320
+ }
321
+
322
+ /**
323
+ * Retrieves the public key properties from a given private key in JWK format.
324
+ *
325
+ * @remarks
326
+ * This method extracts the public key portion from an Ed25519 private key in JWK format. It does
327
+ * so by removing the private key property 'd' and making a shallow copy, effectively yielding the
328
+ * public key. The method sets the 'kid' (key ID) property using the JWK thumbprint if it is not
329
+ * already defined. This approach is used under the assumption that a private key in JWK format
330
+ * always contains the corresponding public key properties.
331
+ *
332
+ * Note: This method offers a significant performance advantage, being about 100 times faster
333
+ * than `computePublicKey()`. However, it does not mathematically validate the private key, nor
334
+ * does it derive the public key from the private key. It simply extracts existing public key
335
+ * properties from the private key object. This makes it suitable for scenarios where speed is
336
+ * critical and the private key's integrity is already assured.
337
+ *
338
+ * @example
339
+ * ```ts
340
+ * const privateKey = { ... }; // A Jwk object representing an Ed25519 private key
341
+ * const publicKey = await Ed25519.getPublicKey({ key: privateKey });
342
+ * ```
343
+ *
344
+ * @param params - The parameters for retrieving the public key properties.
345
+ * @param params.key - The private key in JWK format.
346
+ *
347
+ * @returns A Promise that resolves to the public key in JWK format.
348
+ */
349
+ public static async getPublicKey({ key }:
350
+ GetPublicKeyParams
351
+ ): Promise<Jwk> {
352
+ // Verify the provided JWK represents an octet key pair (OKP) Ed25519 private key.
353
+ if (!(isOkpPrivateJwk(key) && key.crv === 'Ed25519')) {
354
+ throw new Error(`Ed25519: The provided key is not an Ed25519 private JWK.`);
355
+ }
356
+
357
+ // Remove the private key property ('d') and make a shallow copy of the provided key.
358
+ let { d, ...publicKey } = key;
359
+
360
+ // If the key ID is undefined, set it to the JWK thumbprint.
361
+ publicKey.kid ??= await computeJwkThumbprint({ jwk: publicKey });
362
+
363
+ return publicKey;
364
+ }
365
+
366
+ /**
367
+ * Converts a private key from JSON Web Key (JWK) format to a raw byte array (Uint8Array).
368
+ *
369
+ * @remarks
370
+ * This method accepts a private key in JWK format and extracts its raw byte representation.
371
+ *
372
+ * This method accepts a public key in JWK format and converts it into its raw binary
373
+ * form. The conversion process involves decoding the 'd' parameter of the JWK
374
+ * from base64url format into a byte array.
375
+ *
376
+ * @example
377
+ * ```ts
378
+ * const privateKey = { ... }; // An Ed25519 private key in JWK format
379
+ * const privateKeyBytes = await Ed25519.privateKeyToBytes({ privateKey });
380
+ * ```
381
+ *
382
+ * @param params - The parameters for the private key conversion.
383
+ * @param params.privateKey - The private key in JWK format.
384
+ *
385
+ * @returns A Promise that resolves to the private key as a Uint8Array.
386
+ */
387
+ public static async privateKeyToBytes({ privateKey }: {
388
+ privateKey: Jwk;
389
+ }): Promise<Uint8Array> {
390
+ // Verify the provided JWK represents a valid OKP private key.
391
+ if (!isOkpPrivateJwk(privateKey)) {
392
+ throw new Error(`Ed25519: The provided key is not a valid OKP private key.`);
393
+ }
394
+
395
+ // Decode the provided private key to bytes.
396
+ const privateKeyBytes = Convert.base64Url(privateKey.d).toUint8Array();
397
+
398
+ return privateKeyBytes;
399
+ }
400
+
401
+ /**
402
+ * Converts a public key from JSON Web Key (JWK) format to a raw byte array (Uint8Array).
403
+ *
404
+ * @remarks
405
+ * This method accepts a public key in JWK format and converts it into its raw binary form.
406
+ * The conversion process involves decoding the 'x' parameter of the JWK (which represent the
407
+ * x coordinate of the elliptic curve point) from base64url format into a byte array.
408
+ *
409
+ * @example
410
+ * ```ts
411
+ * const publicKey = { ... }; // An Ed25519 public key in JWK format
412
+ * const publicKeyBytes = await Ed25519.publicKeyToBytes({ publicKey });
413
+ * ```
414
+ *
415
+ * @param params - The parameters for the public key conversion.
416
+ * @param params.publicKey - The public key in JWK format.
417
+ *
418
+ * @returns A Promise that resolves to the public key as a Uint8Array.
419
+ */
420
+ public static async publicKeyToBytes({ publicKey }: {
421
+ publicKey: Jwk;
422
+ }): Promise<Uint8Array> {
423
+ // Verify the provided JWK represents a valid OKP public key.
424
+ if (!isOkpPublicJwk(publicKey)) {
425
+ throw new Error(`Ed25519: The provided key is not a valid OKP public key.`);
426
+ }
427
+
428
+ // Decode the provided public key to bytes.
429
+ const publicKeyBytes = Convert.base64Url(publicKey.x).toUint8Array();
430
+
431
+ return publicKeyBytes;
432
+ }
433
+
434
+ /**
435
+ * Generates an RFC8032-compliant EdDSA signature of given data using an Ed25519 private key.
436
+ *
437
+ * @remarks
438
+ * This method signs the provided data with a specified private key using the EdDSA
439
+ * (Edwards-curve Digital Signature Algorithm) as defined in RFC8032. It
440
+ * involves converting the private key from JWK format to a byte array and then employing
441
+ * the Ed25519 algorithm to sign the data. The output is a digital signature in the form
442
+ * of a Uint8Array, uniquely corresponding to both the data and the private key used for
443
+ * signing.
444
+ *
445
+ * @example
446
+ * ```ts
447
+ * const data = new TextEncoder().encode('Messsage'); // Data to be signed
448
+ * const privateKey = { ... }; // A Jwk object representing an Ed25519 private key
449
+ * const signature = await Ed25519.sign({ key: privateKey, data });
450
+ * ```
451
+ *
452
+ * @param params - The parameters for the signing operation.
453
+ * @param params.key - The private key to use for signing, represented in JWK format.
454
+ * @param params.data - The data to sign, represented as a Uint8Array.
455
+ *
456
+ * @returns A Promise that resolves to the signature as a Uint8Array.
457
+ */
458
+ public static async sign({ key, data }:
459
+ SignParams
460
+ ): Promise<Uint8Array> {
461
+ // Convert the private key from JWK format to bytes.
462
+ const privateKeyBytes = await Ed25519.privateKeyToBytes({ privateKey: key });
463
+
464
+ // Sign the provided data using the EdDSA algorithm.
465
+ const signature = ed25519.sign(data, privateKeyBytes);
466
+
467
+ return signature;
468
+ }
469
+
470
+ /**
471
+ * Validates a given public key to confirm its mathematical correctness on the Edwards curve.
472
+ *
473
+ * @remarks
474
+ * This method decodes the Edwards points from the key bytes and asserts their validity on the
475
+ * Curve25519 curve in Twisted Edwards form. If the points are not valid, the method returns
476
+ * false. If the points are valid, the method returns true.
477
+ *
478
+ * Note that this validation strictly pertains to the key's format and numerical validity; it does
479
+ * not assess whether the key corresponds to a known entity or its security status (e.g., whether
480
+ * it has been compromised).
481
+ *
482
+ * @example
483
+ * ```ts
484
+ * const publicKeyBytes = new Uint8Array([...]); // A public key in byte format
485
+ * const isValid = await Ed25519.validatePublicKey({ publicKeyBytes });
486
+ * console.log(isValid); // true if the key is valid on the Edwards curve, false otherwise
487
+ * ```
488
+ *
489
+ * @param params - The parameters for the public key validation.
490
+ * @param params.publicKeyBytes - The public key to validate, represented as a Uint8Array.
491
+ *
492
+ * @returns A Promise that resolves to a boolean indicating whether the key
493
+ * corresponds to a valid point on the Edwards curve.
494
+ */
495
+ public static async validatePublicKey({ publicKeyBytes }: {
496
+ publicKeyBytes: Uint8Array;
497
+ }): Promise<boolean> {
498
+ try {
499
+ // Decode Edwards points from key bytes.
500
+ const point = ed25519.ExtendedPoint.fromHex(publicKeyBytes);
501
+
502
+ // Check if points are on the Twisted Edwards curve.
503
+ point.assertValidity();
504
+
505
+ } catch(error: any) {
506
+ return false;
507
+ }
508
+
509
+ return true;
510
+ }
511
+
512
+ /**
513
+ * Verifies an RFC8032-compliant EdDSA signature against given data using an Ed25519 public key.
514
+ *
515
+ * @remarks
516
+ * This method validates a digital signature to ensure its authenticity and integrity.
517
+ * It uses the EdDSA (Edwards-curve Digital Signature Algorithm) as specified in RFC8032.
518
+ * The verification process involves converting the public key from JWK format to a raw
519
+ * byte array and using the Ed25519 algorithm to validate the signature against the provided data.
520
+ *
521
+ * @example
522
+ * ```ts
523
+ * const data = new TextEncoder().encode('Messsage'); // Data that was signed
524
+ * const publicKey = { ... }; // A Jwk object representing an Ed25519 public key
525
+ * const signature = new Uint8Array([...]); // Signature to verify
526
+ * const isValid = await Ed25519.verify({ key: publicKey, signature, data });
527
+ * console.log(isValid); // true if the signature is valid, false otherwise
528
+ * ```
529
+ *
530
+ * @param params - The parameters for the signature verification.
531
+ * @param params.key - The public key in JWK format used for verification.
532
+ * @param params.signature - The signature to verify, represented as a Uint8Array.
533
+ * @param params.data - The data that was signed, represented as a Uint8Array.
534
+ *
535
+ * @returns A Promise that resolves to a boolean indicating whether the signature is valid.
536
+ */
537
+ public static async verify({ key, signature, data }:
538
+ VerifyParams
539
+ ): Promise<boolean> {
540
+ // Convert the public key from JWK format to bytes.
541
+ const publicKeyBytes = await Ed25519.publicKeyToBytes({ publicKey: key });
542
+
543
+ // Perform the verification of the signature.
544
+ const isValid = ed25519.verify(signature, data, publicKeyBytes);
545
+
546
+ return isValid;
547
+ }
548
+ }
@@ -0,0 +1,122 @@
1
+ import { crypto } from '@noble/hashes/crypto';
2
+
3
+ /**
4
+ * The object that should be passed into `Pbkdf2.deriveKey()`, when using the PBKDF2 algorithm.
5
+ */
6
+ export type Pbkdf2DeriveKeyParams = {
7
+ /**
8
+ * A string representing the digest algorithm to use. This may be one of:
9
+ * - 'SHA-256'
10
+ * - 'SHA-384'
11
+ * - 'SHA-512'
12
+ */
13
+ hash: 'SHA-256' | 'SHA-384' | 'SHA-512';
14
+
15
+ /**
16
+ * The password from which to derive the key, represented as a Uint8Array.
17
+ */
18
+ password: Uint8Array;
19
+
20
+ /**
21
+ * The salt value to use in the derivation process, as a Uint8Array. This should be a random or
22
+ * pseudo-random value of at least 16 bytes. Unlike the `password`, `salt` does not need to be
23
+ * kept secret.
24
+ */
25
+ salt: Uint8Array;
26
+
27
+ /**
28
+ * A `Number` representing the number of iterations the hash function will be executed in
29
+ * `deriveKey()`. This impacts the computational cost of the `deriveKey()` operation, making it
30
+ * more resistant to dictionary attacks. The higher the number, the more secure, but also slower,
31
+ * the operation. Choose a value that balances security needs and performance for your
32
+ * application.
33
+ */
34
+ iterations: number;
35
+
36
+ /**
37
+ * The desired length of the derived key in bits. To be compatible with all browsers, the number
38
+ * should be a multiple of 8.
39
+ */
40
+ length: number;
41
+ };
42
+
43
+ /**
44
+ * The `Pbkdf2` class provides a secure way to derive cryptographic keys from a password
45
+ * using the PBKDF2 (Password-Based Key Derivation Function 2) algorithm.
46
+ *
47
+ * The PBKDF2 algorithm is widely used for generating keys from passwords, as it applies
48
+ * a pseudorandom function to the input password along with a salt value and iterates the
49
+ * process multiple times to increase the key's resistance to brute-force attacks.
50
+ *
51
+ * This class offers a single static method `deriveKey` to perform key derivation.
52
+ *
53
+ * @example
54
+ * ```ts
55
+ * // Key Derivation
56
+ * const derivedKey = await Pbkdf2.deriveKey({
57
+ * hash: 'SHA-256', // The hash function to use ('SHA-256', 'SHA-384', 'SHA-512')
58
+ * password: new TextEncoder().encode('password'), // The password as a Uint8Array
59
+ * salt: new Uint8Array([...]), // The salt value
60
+ * iterations: 1000, // The number of iterations
61
+ * length: 256 // The length of the derived key in bits
62
+ * });
63
+ * ```
64
+ *
65
+ * @remarks
66
+ * This class relies on the availability of the Web Crypto API.
67
+ */
68
+ export class Pbkdf2 {
69
+ /**
70
+ * Derives a cryptographic key from a password using the PBKDF2 algorithm.
71
+ *
72
+ * @remarks
73
+ * This method applies the PBKDF2 algorithm to the provided password along with
74
+ * a salt value and iterates the process a specified number of times. It uses
75
+ * a cryptographic hash function to enhance security and produce a key of the
76
+ * desired length. The method is capable of utilizing either the Web Crypto API
77
+ * or the Node.js Crypto module, depending on the environment's support.
78
+ *
79
+ * @example
80
+ * ```ts
81
+ * const derivedKey = await Pbkdf2.deriveKey({
82
+ * hash: 'SHA-256',
83
+ * password: new TextEncoder().encode('password'),
84
+ * salt: new Uint8Array([...]),
85
+ * iterations: 1000,
86
+ * length: 256
87
+ * });
88
+ * ```
89
+ *
90
+ * @param params - The parameters for key derivation.
91
+ * @param params.hash - The hash function to use, such as 'SHA-256', 'SHA-384', or 'SHA-512'.
92
+ * @param params.password - The password from which to derive the key, represented as a Uint8Array.
93
+ * @param params.salt - The salt value to use in the derivation process, as a Uint8Array.
94
+ * @param params.iterations - The number of iterations to apply in the PBKDF2 algorithm.
95
+ * @param params.length - The desired length of the derived key in bits.
96
+ *
97
+ * @returns A Promise that resolves to the derived key as a Uint8Array.
98
+ */
99
+ public static async deriveKey({ hash, password, salt, iterations, length }:
100
+ Pbkdf2DeriveKeyParams
101
+ ): Promise<Uint8Array> {
102
+ // Import the password as a raw key for use with the Web Crypto API.
103
+ const webCryptoKey = await crypto.subtle.importKey(
104
+ 'raw',
105
+ password,
106
+ { name: 'PBKDF2' },
107
+ false,
108
+ ['deriveBits']
109
+ );
110
+
111
+ const derivedKeyBuffer = await crypto.subtle.deriveBits(
112
+ { name: 'PBKDF2', hash, salt, iterations },
113
+ webCryptoKey,
114
+ length
115
+ );
116
+
117
+ // Convert from ArrayBuffer to Uint8Array.
118
+ const derivedKey = new Uint8Array(derivedKeyBuffer);
119
+
120
+ return derivedKey;
121
+ }
122
+ }