@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,850 @@
1
+ import type { AffinePoint } from '@noble/curves/abstract/weierstrass';
2
+
3
+ import { Convert } from '@enbox/common';
4
+ import { sha256 } from '@noble/hashes/sha256';
5
+ import { secp256r1 } from '@noble/curves/p256';
6
+ import { numberToBytesBE } from '@noble/curves/abstract/utils';
7
+
8
+ import type { Jwk } from '../jose/jwk.js';
9
+ import type { ComputePublicKeyParams, GetPublicKeyParams, SignParams, VerifyParams } from '../types/params-direct.js';
10
+
11
+ import { computeJwkThumbprint, isEcPrivateJwk, isEcPublicJwk } from '../jose/jwk.js';
12
+
13
+ /**
14
+ * The `Secp256r1` class provides a comprehensive suite of utilities for working with
15
+ * the secp256r1 (aka P-256) elliptic curve, commonly used in blockchain and cryptographic
16
+ * applications. This class includes methods for key generation, conversion, signing, verification,
17
+ * and Elliptic Curve Diffie-Hellman (ECDH) key agreement.
18
+ *
19
+ * The class supports conversions between raw byte formats and JSON Web Key (JWK) formats. It
20
+ * adheres to RFC6979 for ECDSA signing and verification and RFC6090 for ECDH.
21
+ *
22
+ * Key Features:
23
+ * - Key Generation: Generate secp256r1 private keys in JWK format.
24
+ * - Key Conversion: Transform keys between raw byte arrays and JWK formats.
25
+ * - Public Key Derivation: Derive public keys from private keys.
26
+ * - ECDH Shared Secret Computation: Securely derive shared secrets using private and public keys.
27
+ * - ECDSA Signing and Verification: Sign data and verify signatures with secp256r1 keys.
28
+ * - Key Validation: Validate the mathematical correctness of secp256r1 keys.
29
+ *
30
+ * The methods in this class are asynchronous, returning Promises to accommodate various
31
+ * JavaScript environments, and use `Uint8Array` for binary data handling.
32
+ *
33
+ * @example
34
+ * ```ts
35
+ * // Key Generation
36
+ * const privateKey = await Secp256r1.generateKey();
37
+ *
38
+ * // Public Key Derivation
39
+ * const publicKey = await Secp256r1.computePublicKey({ key: privateKey });
40
+ * console.log(publicKey === await Secp256r1.getPublicKey({ key: privateKey })); // Output: true
41
+ *
42
+ * // ECDH Shared Secret Computation
43
+ * const sharedSecret = await Secp256r1.sharedSecret({
44
+ * privateKeyA: privateKey,
45
+ * publicKeyB: anotherPublicKey
46
+ * });
47
+ *
48
+ * // ECDSA Signing
49
+ * const signature = await Secp256r1.sign({
50
+ * key: privateKey,
51
+ * data: new TextEncoder().encode('Message')
52
+ * });
53
+ *
54
+ * // ECDSA Signature Verification
55
+ * const isValid = await Secp256r1.verify({
56
+ * key: publicKey,
57
+ * signature: signature,
58
+ * data: new TextEncoder().encode('Message')
59
+ * });
60
+ *
61
+ * // Key Conversion
62
+ * const publicKeyBytes = await Secp256r1.publicKeyToBytes({ publicKey });
63
+ * const privateKeyBytes = await Secp256r1.privateKeyToBytes({ privateKey });
64
+ * const compressedPublicKey = await Secp256r1.compressPublicKey({ publicKeyBytes });
65
+ * const uncompressedPublicKey = await Secp256r1.decompressPublicKey({ publicKeyBytes });
66
+ *
67
+ * // Key Validation
68
+ * const isPrivateKeyValid = await Secp256r1.validatePrivateKey({ privateKeyBytes });
69
+ * const isPublicKeyValid = await Secp256r1.validatePublicKey({ publicKeyBytes });
70
+ * ```
71
+ */
72
+ export class Secp256r1 {
73
+ /**
74
+ * Adjusts an ECDSA signature to a normalized, low-S form.
75
+ *
76
+ * @remarks
77
+ * All ECDSA signatures, regardless of the curve, consist of two components, `r` and `s`, both of
78
+ * which are integers. The curve's order (the total number of points on the curve) is denoted by
79
+ * `n`. In a valid ECDSA signature, both `r` and `s` must be in the range [1, n-1]. However, due
80
+ * to the mathematical properties of ECDSA, if `(r, s)` is a valid signature, then `(r, n - s)` is
81
+ * also a valid signature for the same message and public key. In other words, for every
82
+ * signature, there's a "mirror" signature that's equally valid. For these elliptic curves:
83
+ *
84
+ * - Low S Signature: A signature where the `s` component is in the lower half of the range,
85
+ * specifically less than or equal to `n/2`.
86
+ *
87
+ * - High S Signature: This is where the `s` component is in the upper half of the range, greater
88
+ * than `n/2`.
89
+ *
90
+ * The practical implication is that a third-party can forge a second valid signature for the same
91
+ * message by negating the `s` component of the original signature, without any knowledge of the
92
+ * private key. This is known as a "signature malleability" attack.
93
+ *
94
+ * This type of forgery is not a problem in all systems, but it can be an issue in systems that
95
+ * rely on digital signature uniqueness to ensure transaction integrity. For example, in Bitcoin,
96
+ * transaction malleability is an issue because it allows for the modification of transaction
97
+ * identifiers (and potentially, transactions themselves) after they're signed but before they're
98
+ * confirmed in a block. By enforcing low `s` values, the Bitcoin network reduces the likelihood of
99
+ * this occurring, making the system more secure and predictable.
100
+ *
101
+ * For this reason, it's common practice to normalize ECDSA signatures to a low-S form. This
102
+ * form is considered standard and preferable in some systems and is known as the "normalized"
103
+ * form of the signature.
104
+ *
105
+ * This method takes a signature, and if it's high-S, returns the normalized low-S form. If the
106
+ * signature is already low-S, it's returned unmodified. It's important to note that this
107
+ * method does not change the validity of the signature but makes it compliant with systems that
108
+ * enforce low-S signatures.
109
+ *
110
+ * @example
111
+ * ```ts
112
+ * const signature = new Uint8Array([...]); // Your ECDSA signature
113
+ * const adjustedSignature = await Secp256r1.adjustSignatureToLowS({ signature });
114
+ * // Now 'adjustedSignature' is in the low-S form.
115
+ * ```
116
+ *
117
+ * @param params - The parameters for the signature adjustment.
118
+ * @param params.signature - The ECDSA signature as a `Uint8Array`.
119
+ *
120
+ * @returns A Promise that resolves to the adjusted signature in low-S form as a `Uint8Array`.
121
+ */
122
+ public static async adjustSignatureToLowS({ signature }: {
123
+ signature: Uint8Array;
124
+ }): Promise<Uint8Array> {
125
+ // Convert the signature to a `Secp256r1.Signature` object.
126
+ const signatureObject = secp256r1.Signature.fromCompact(signature);
127
+
128
+ if (signatureObject.hasHighS()) {
129
+ // Adjust the signature to low-S format if it's high-S.
130
+ const adjustedSignatureObject = signatureObject.normalizeS();
131
+
132
+ // Convert the adjusted signature object back to a byte array.
133
+ const adjustedSignature = adjustedSignatureObject.toCompactRawBytes();
134
+
135
+ return adjustedSignature;
136
+
137
+ } else {
138
+ // Return the unmodified signature if it is already in low-S format.
139
+ return signature;
140
+ }
141
+ }
142
+
143
+ /**
144
+ * Converts a raw private key in bytes to its corresponding JSON Web Key (JWK) format.
145
+ *
146
+ * @remarks
147
+ * This method takes a private key represented as a byte array (Uint8Array) and
148
+ * converts it into a JWK object. The conversion involves extracting the
149
+ * elliptic curve point (x and y coordinates) from the private key and encoding
150
+ * them into base64url format, alongside other JWK parameters.
151
+ *
152
+ * The resulting JWK object includes the following properties:
153
+ * - `kty`: Key Type, set to 'EC' for Elliptic Curve.
154
+ * - `crv`: Curve Name, set to 'P-256'.
155
+ * - `d`: The private key component, base64url-encoded.
156
+ * - `x`: The x-coordinate of the public key point, base64url-encoded.
157
+ * - `y`: The y-coordinate of the public key point, base64url-encoded.
158
+ *
159
+ * This method is useful for converting raw public keys into a standardized
160
+ * JSON format, facilitating their use in cryptographic operations and making
161
+ * them easy to share and store.
162
+ *
163
+ * @example
164
+ * ```ts
165
+ * const privateKeyBytes = new Uint8Array([...]); // Replace with actual private key bytes
166
+ * const privateKey = await Secp256r1.bytesToPrivateKey({ privateKeyBytes });
167
+ * ```
168
+ *
169
+ * @param params - The parameters for the private key conversion.
170
+ * @param params.privateKeyBytes - The raw private key as a Uint8Array.
171
+ *
172
+ * @returns A Promise that resolves to the private key in JWK format.
173
+ */
174
+ public static async bytesToPrivateKey({ privateKeyBytes }: {
175
+ privateKeyBytes: Uint8Array;
176
+ }): Promise<Jwk> {
177
+ // Get the elliptic curve points (x and y coordinates) for the provided private key.
178
+ const point = await Secp256r1.getCurvePoint({ keyBytes: privateKeyBytes });
179
+
180
+ // Construct the private key in JWK format.
181
+ const privateKey: Jwk = {
182
+ kty : 'EC',
183
+ crv : 'P-256',
184
+ d : Convert.uint8Array(privateKeyBytes).toBase64Url(),
185
+ x : Convert.uint8Array(point.x).toBase64Url(),
186
+ y : Convert.uint8Array(point.y).toBase64Url()
187
+ };
188
+
189
+ // Compute the JWK thumbprint and set as the key ID.
190
+ privateKey.kid = await computeJwkThumbprint({ jwk: privateKey });
191
+
192
+ return privateKey;
193
+ }
194
+
195
+ /**
196
+ * Converts a raw public key in bytes to its corresponding JSON Web Key (JWK) format.
197
+ *
198
+ * @remarks
199
+ * This method accepts a public key in a byte array (Uint8Array) format and
200
+ * transforms it to a JWK object. It involves decoding the elliptic curve point
201
+ * (x and y coordinates) from the raw public key bytes and encoding them into
202
+ * base64url format, along with setting appropriate JWK parameters.
203
+ *
204
+ * The resulting JWK object includes the following properties:
205
+ * - `kty`: Key Type, set to 'EC' for Elliptic Curve.
206
+ * - `crv`: Curve Name, set to 'P-256'.
207
+ * - `x`: The x-coordinate of the public key point, base64url-encoded.
208
+ * - `y`: The y-coordinate of the public key point, base64url-encoded.
209
+ *
210
+ * This method is useful for converting raw public keys into a standardized
211
+ * JSON format, facilitating their use in cryptographic operations and making
212
+ * them easy to share and store.
213
+ *
214
+ * @example
215
+ * ```ts
216
+ * const publicKeyBytes = new Uint8Array([...]); // Replace with actual public key bytes
217
+ * const publicKey = await Secp256r1.bytesToPublicKey({ publicKeyBytes });
218
+ * ```
219
+ *
220
+ * @param params - The parameters for the public key conversion.
221
+ * @param params.publicKeyBytes - The raw public key as a Uint8Array.
222
+ *
223
+ * @returns A Promise that resolves to the public key in JWK format.
224
+ */
225
+ public static async bytesToPublicKey({ publicKeyBytes }: {
226
+ publicKeyBytes: Uint8Array;
227
+ }): Promise<Jwk> {
228
+ // Get the elliptic curve point (x and y coordinates) for the provided public key.
229
+ const point = await Secp256r1.getCurvePoint({ keyBytes: publicKeyBytes });
230
+
231
+ // Construct the public key in JWK format.
232
+ const publicKey: Jwk = {
233
+ kty : 'EC',
234
+ crv : 'P-256',
235
+ x : Convert.uint8Array(point.x).toBase64Url(),
236
+ y : Convert.uint8Array(point.y).toBase64Url()
237
+ };
238
+
239
+ // Compute the JWK thumbprint and set as the key ID.
240
+ publicKey.kid = await computeJwkThumbprint({ jwk: publicKey });
241
+
242
+ return publicKey;
243
+ }
244
+
245
+ /**
246
+ * Converts a public key to its compressed form.
247
+ *
248
+ * @remarks
249
+ * This method takes a public key represented as a byte array and compresses it. Public key
250
+ * compression is a process that reduces the size of the public key by removing the y-coordinate,
251
+ * making it more efficient for storage and transmission. The compressed key retains the same
252
+ * level of security as the uncompressed key.
253
+ *
254
+ * @example
255
+ * ```ts
256
+ * const uncompressedPublicKeyBytes = new Uint8Array([...]); // Replace with actual uncompressed public key bytes
257
+ * const compressedPublicKey = await Secp256r1.compressPublicKey({
258
+ * publicKeyBytes: uncompressedPublicKeyBytes
259
+ * });
260
+ * ```
261
+ *
262
+ * @param params - The parameters for the public key compression.
263
+ * @param params.publicKeyBytes - The public key as a Uint8Array.
264
+ *
265
+ * @returns A Promise that resolves to the compressed public key as a Uint8Array.
266
+ */
267
+ public static async compressPublicKey({ publicKeyBytes }: {
268
+ publicKeyBytes: Uint8Array;
269
+ }): Promise<Uint8Array> {
270
+ // Decode Weierstrass points from the public key byte array.
271
+ const point = secp256r1.ProjectivePoint.fromHex(publicKeyBytes);
272
+
273
+ // Return the compressed form of the public key.
274
+ return point.toRawBytes(true);
275
+ }
276
+
277
+ /**
278
+ * Derives the public key in JWK format from a given private key.
279
+ *
280
+ * @remarks
281
+ * This method takes a private key in JWK format and derives its corresponding public key,
282
+ * also in JWK format. The derivation process involves converting the private key to a raw
283
+ * byte array, then computing the elliptic curve point (x and y coordinates) from this private
284
+ * key. These coordinates are then encoded into base64url format to construct the public key in
285
+ * JWK format.
286
+ *
287
+ * The process ensures that the derived public key correctly corresponds to the given private key,
288
+ * adhering to the secp256r1 elliptic curve standards. This method is useful in cryptographic
289
+ * operations where a public key is needed for operations like signature verification, but only
290
+ * the private key is available.
291
+ *
292
+ * @example
293
+ * ```ts
294
+ * const privateKey = { ... }; // A Jwk object representing a secp256r1 private key
295
+ * const publicKey = await Secp256r1.computePublicKey({ key: privateKey });
296
+ * ```
297
+ *
298
+ * @param params - The parameters for the public key derivation.
299
+ * @param params.key - The private key in JWK format from which to derive the public key.
300
+ *
301
+ * @returns A Promise that resolves to the derived public key in JWK format.
302
+ */
303
+ public static async computePublicKey({ key }:
304
+ ComputePublicKeyParams
305
+ ): Promise<Jwk> {
306
+ // Convert the provided private key to a byte array.
307
+ const privateKeyBytes = await Secp256r1.privateKeyToBytes({ privateKey: key });
308
+
309
+ // Get the elliptic curve point (x and y coordinates) for the provided private key.
310
+ const point = await Secp256r1.getCurvePoint({ keyBytes: privateKeyBytes });
311
+
312
+ // Construct the public key in JWK format.
313
+ const publicKey: Jwk = {
314
+ kty : 'EC',
315
+ crv : 'P-256',
316
+ x : Convert.uint8Array(point.x).toBase64Url(),
317
+ y : Convert.uint8Array(point.y).toBase64Url()
318
+ };
319
+
320
+ // Compute the JWK thumbprint and set as the key ID.
321
+ publicKey.kid = await computeJwkThumbprint({ jwk: publicKey });
322
+
323
+ return publicKey;
324
+ }
325
+
326
+ /**
327
+ * Converts an ASN.1 DER encoded ECDSA signature to a compact R+S format.
328
+ *
329
+ * @remarks
330
+ * This method is used for converting an ECDSA signature from the ASN.1 DER encoding to the more
331
+ * compact R+S format. This conversion is often required when dealing with ECDSA signatures in
332
+ * certain cryptographic standards such as JWS (JSON Web Signature).
333
+ *
334
+ * The method decodes the DER-encoded signature, extracts the R and S values, and concatenates
335
+ * them into a single byte array. This process involves handling the ASN.1 structure to correctly
336
+ * parse the R and S values, considering padding and integer encoding specifics of DER.
337
+ *
338
+ * @example
339
+ * ```ts
340
+ * const derSignature = new Uint8Array([...]); // Replace with your DER-encoded signature
341
+ * const signature = await Secp256r1.convertDerToCompactSignature({ derSignature });
342
+ * ```
343
+ *
344
+ * @param params - The parameters for the signature conversion.
345
+ * @param params.derSignature - The signature in ASN.1 DER format as a `Uint8Array`.
346
+ *
347
+ * @returns A Promise that resolves to the signature in compact R+S format as a `Uint8Array`.
348
+ */
349
+ public static async convertDerToCompactSignature({ derSignature }: {
350
+ derSignature: Uint8Array;
351
+ }): Promise<Uint8Array> {
352
+ // Convert the DER-encoded signature into a `Secp256r1.Signature` object.
353
+ // This involves parsing the ASN.1 DER structure to extract the R and S components.
354
+ const signatureObject = secp256r1.Signature.fromDER(derSignature);
355
+
356
+ // Convert the signature object into compact R+S format, which concatenates the R and S values
357
+ // into a single byte array.
358
+ const compactSignature = signatureObject.toCompactRawBytes();
359
+
360
+ return compactSignature;
361
+ }
362
+
363
+ /**
364
+ * Converts a public key to its uncompressed form.
365
+ *
366
+ * @remarks
367
+ * This method takes a compressed public key represented as a byte array and decompresses it.
368
+ * Public key decompression involves reconstructing the y-coordinate from the x-coordinate,
369
+ * resulting in the full public key. This method is used when the uncompressed key format is
370
+ * required for certain cryptographic operations or interoperability.
371
+ *
372
+ * @example
373
+ * ```ts
374
+ * const compressedPublicKeyBytes = new Uint8Array([...]); // Replace with actual compressed public key bytes
375
+ * const decompressedPublicKey = await Secp256r1.decompressPublicKey({
376
+ * publicKeyBytes: compressedPublicKeyBytes
377
+ * });
378
+ * ```
379
+ *
380
+ * @param params - The parameters for the public key decompression.
381
+ * @param params.publicKeyBytes - The public key as a Uint8Array.
382
+ *
383
+ * @returns A Promise that resolves to the uncompressed public key as a Uint8Array.
384
+ */
385
+ public static async decompressPublicKey({ publicKeyBytes }: {
386
+ publicKeyBytes: Uint8Array;
387
+ }): Promise<Uint8Array> {
388
+ // Decode Weierstrass points from the public key byte array.
389
+ const point = secp256r1.ProjectivePoint.fromHex(publicKeyBytes);
390
+
391
+ // Return the uncompressed form of the public key.
392
+ return point.toRawBytes(false);
393
+ }
394
+
395
+ /**
396
+ * Generates a secp256r1 private key in JSON Web Key (JWK) format.
397
+ *
398
+ * @remarks
399
+ * This method creates a new private key suitable for use with the secp256r1
400
+ * elliptic curve. The key is generated using cryptographically secure random
401
+ * number generation to ensure its uniqueness and security. The resulting
402
+ * private key adheres to the JWK format, specifically tailored for secp256r1,
403
+ * making it compatible with common cryptographic standards and easy to use in
404
+ * various cryptographic processes.
405
+ *
406
+ * The private key generated by this method includes the following components:
407
+ * - `kty`: Key Type, set to 'EC' for Elliptic Curve.
408
+ * - `crv`: Curve Name, set to 'P-256'.
409
+ * - `d`: The private key component, base64url-encoded.
410
+ * - `x`: The x-coordinate of the public key point, derived from the private key, base64url-encoded.
411
+ * - `y`: The y-coordinate of the public key point, derived from the private key, base64url-encoded.
412
+ *
413
+ * The key is returned in a format suitable for direct use in signin and key agreement operations.
414
+ *
415
+ * @example
416
+ * ```ts
417
+ * const privateKey = await Secp256r1.generateKey();
418
+ * ```
419
+ *
420
+ * @returns A Promise that resolves to the generated private key in JWK format.
421
+ */
422
+ public static async generateKey(): Promise<Jwk> {
423
+ // Generate a random private key.
424
+ const privateKeyBytes = secp256r1.utils.randomPrivateKey();
425
+
426
+ // Convert private key from bytes to JWK format.
427
+ const privateKey = await Secp256r1.bytesToPrivateKey({ privateKeyBytes });
428
+
429
+ // Compute the JWK thumbprint and set as the key ID.
430
+ privateKey.kid = await computeJwkThumbprint({ jwk: privateKey });
431
+
432
+ return privateKey;
433
+ }
434
+
435
+ /**
436
+ * Retrieves the public key properties from a given private key in JWK format.
437
+ *
438
+ * @remarks
439
+ * This method extracts the public key portion from a secp256r1 private key in JWK format. It does
440
+ * so by removing the private key property 'd' and making a shallow copy, effectively yielding the
441
+ * public key. The method sets the 'kid' (key ID) property using the JWK thumbprint if it is not
442
+ * already defined. This approach is used under the assumption that a private key in JWK format
443
+ * always contains the corresponding public key properties.
444
+ *
445
+ * Note: This method offers a significant performance advantage, being about 200 times faster
446
+ * than `computePublicKey()`. However, it does not mathematically validate the private key, nor
447
+ * does it derive the public key from the private key. It simply extracts existing public key
448
+ * properties from the private key object. This makes it suitable for scenarios where speed is
449
+ * critical and the private key's integrity is already assured.
450
+ *
451
+ * @example
452
+ * ```ts
453
+ * const privateKey = { ... }; // A Jwk object representing a secp256r1 private key
454
+ * const publicKey = await Secp256r1.getPublicKey({ key: privateKey });
455
+ * ```
456
+ *
457
+ * @param params - The parameters for retrieving the public key properties.
458
+ * @param params.key - The private key in JWK format.
459
+ *
460
+ * @returns A Promise that resolves to the public key in JWK format.
461
+ */
462
+ public static async getPublicKey({ key }:
463
+ GetPublicKeyParams
464
+ ): Promise<Jwk> {
465
+ // Verify the provided JWK represents an elliptic curve (EC) secp256r1 private key.
466
+ if (!(isEcPrivateJwk(key) && key.crv === 'P-256')) {
467
+ throw new Error(`Secp256r1: The provided key is not a 'P-256' private JWK.`);
468
+ }
469
+
470
+ // Remove the private key property ('d') and make a shallow copy of the provided key.
471
+ let { d, ...publicKey } = key;
472
+
473
+ // If the key ID is undefined, set it to the JWK thumbprint.
474
+ publicKey.kid ??= await computeJwkThumbprint({ jwk: publicKey });
475
+
476
+ return publicKey;
477
+ }
478
+
479
+ /**
480
+ * Converts a private key from JSON Web Key (JWK) format to a raw byte array (Uint8Array).
481
+ *
482
+ * @remarks
483
+ * This method takes a private key in JWK format and extracts its raw byte representation.
484
+ * It specifically focuses on the 'd' parameter of the JWK, which represents the private
485
+ * key component in base64url encoding. The method decodes this value into a byte array.
486
+ *
487
+ * This conversion is essential for operations that require the private key in its raw
488
+ * binary form, such as certain low-level cryptographic operations or when interfacing
489
+ * with systems and libraries that expect keys in a byte array format.
490
+ *
491
+ * @example
492
+ * ```ts
493
+ * const privateKey = { ... }; // An X25519 private key in JWK format
494
+ * const privateKeyBytes = await Secp256r1.privateKeyToBytes({ privateKey });
495
+ * ```
496
+ *
497
+ * @param params - The parameters for the private key conversion.
498
+ * @param params.privateKey - The private key in JWK format.
499
+ *
500
+ * @returns A Promise that resolves to the private key as a Uint8Array.
501
+ */
502
+ public static async privateKeyToBytes({ privateKey }: {
503
+ privateKey: Jwk;
504
+ }): Promise<Uint8Array> {
505
+ // Verify the provided JWK represents a valid EC P-256 private key.
506
+ if (!isEcPrivateJwk(privateKey)) {
507
+ throw new Error(`Secp256r1: The provided key is not a valid EC private key.`);
508
+ }
509
+
510
+ // Decode the provided private key to bytes.
511
+ const privateKeyBytes = Convert.base64Url(privateKey.d).toUint8Array();
512
+
513
+ return privateKeyBytes;
514
+ }
515
+
516
+ /**
517
+ * Converts a public key from JSON Web Key (JWK) format to a raw byte array (Uint8Array).
518
+ *
519
+ * @remarks
520
+ * This method accepts a public key in JWK format and converts it into its raw binary
521
+ * form. The conversion process involves decoding the 'x' and 'y' parameters of the JWK
522
+ * (which represent the x and y coordinates of the elliptic curve point, respectively)
523
+ * from base64url format into a byte array. The method then concatenates these values,
524
+ * along with a prefix indicating the key format, to form the full public key.
525
+ *
526
+ * This function is particularly useful for use cases where the public key is needed
527
+ * in its raw byte format, such as for certain cryptographic operations or when
528
+ * interfacing with systems that require raw key formats.
529
+ *
530
+ * @example
531
+ * ```ts
532
+ * const publicKey = { ... }; // A Jwk public key object
533
+ * const publicKeyBytes = await Secp256r1.publicKeyToBytes({ publicKey });
534
+ * ```
535
+ *
536
+ * @param params - The parameters for the public key conversion.
537
+ * @param params.publicKey - The public key in JWK format.
538
+ *
539
+ * @returns A Promise that resolves to the public key as a Uint8Array.
540
+ */
541
+ public static async publicKeyToBytes({ publicKey }: {
542
+ publicKey: Jwk;
543
+ }): Promise<Uint8Array> {
544
+ // Verify the provided JWK represents a valid EC P-256 public key, which must have a 'y' value.
545
+ if (!(isEcPublicJwk(publicKey) && publicKey.y)) {
546
+ throw new Error(`Secp256r1: The provided key is not a valid EC public key.`);
547
+ }
548
+
549
+ // Decode the provided public key to bytes.
550
+ const prefix = new Uint8Array([0x04]); // Designates an uncompressed key.
551
+ const x = Convert.base64Url(publicKey.x).toUint8Array();
552
+ const y = Convert.base64Url(publicKey.y).toUint8Array();
553
+
554
+ // Concatenate the prefix, x-coordinate, and y-coordinate as a single byte array.
555
+ const publicKeyBytes = new Uint8Array([...prefix, ...x, ...y]);
556
+
557
+ return publicKeyBytes;
558
+ }
559
+
560
+ /**
561
+ * Computes an RFC6090-compliant Elliptic Curve Diffie-Hellman (ECDH) shared secret
562
+ * using secp256r1 private and public keys in JSON Web Key (JWK) format.
563
+ *
564
+ * @remarks
565
+ * This method facilitates the ECDH key agreement protocol, which is a method of securely
566
+ * deriving a shared secret between two parties based on their private and public keys.
567
+ * It takes the private key of one party (privateKeyA) and the public key of another
568
+ * party (publicKeyB) to compute a shared secret. The shared secret is derived from the
569
+ * x-coordinate of the elliptic curve point resulting from the multiplication of the
570
+ * public key with the private key.
571
+ *
572
+ * Note: When performing Elliptic Curve Diffie-Hellman (ECDH) key agreement,
573
+ * the resulting shared secret is a point on the elliptic curve, which
574
+ * consists of an x-coordinate and a y-coordinate. With a 256-bit curve like
575
+ * secp256r1, each of these coordinates is 32 bytes (256 bits) long. However,
576
+ * in the ECDH process, it's standard practice to use only the x-coordinate
577
+ * of the shared secret point as the resulting shared key. This is because
578
+ * the y-coordinate does not add to the entropy of the key, and both parties
579
+ * can independently compute the x-coordinate. Consquently, this implementation
580
+ * omits the y-coordinate for simplicity and standard compliance.
581
+ *
582
+ * @example
583
+ * ```ts
584
+ * const privateKeyA = { ... }; // A Jwk private key object for party A
585
+ * const publicKeyB = { ... }; // A Jwk public key object for party B
586
+ * const sharedSecret = await Secp256r1.sharedSecret({
587
+ * privateKeyA,
588
+ * publicKeyB
589
+ * });
590
+ * ```
591
+ *
592
+ * @param params - The parameters for the shared secret computation.
593
+ * @param params.privateKeyA - The private key in JWK format of one party.
594
+ * @param params.publicKeyB - The public key in JWK format of the other party.
595
+ *
596
+ * @returns A Promise that resolves to the computed shared secret as a Uint8Array.
597
+ */
598
+ public static async sharedSecret({ privateKeyA, publicKeyB }: {
599
+ privateKeyA: Jwk;
600
+ publicKeyB: Jwk;
601
+ }): Promise<Uint8Array> {
602
+ // Ensure that keys from the same key pair are not specified.
603
+ if ('x' in privateKeyA && 'x' in publicKeyB && privateKeyA.x === publicKeyB.x) {
604
+ throw new Error(`Secp256r1: ECDH shared secret cannot be computed from a single key pair's public and private keys.`);
605
+ }
606
+
607
+ // Convert the provided private and public keys to bytes.
608
+ const privateKeyABytes = await Secp256r1.privateKeyToBytes({ privateKey: privateKeyA });
609
+ const publicKeyBBytes = await Secp256r1.publicKeyToBytes({ publicKey: publicKeyB });
610
+
611
+ // Compute the compact representation shared secret between the public and private keys.
612
+ const sharedSecret = secp256r1.getSharedSecret(privateKeyABytes, publicKeyBBytes, true);
613
+
614
+ // Remove the leading byte that indicates the sign of the y-coordinate
615
+ // of the point on the elliptic curve. See note above.
616
+ return sharedSecret.slice(1);
617
+ }
618
+
619
+ /**
620
+ * Generates an RFC6979-compliant ECDSA signature of given data using a secp256r1 private key.
621
+ *
622
+ * @remarks
623
+ * This method signs the provided data with a specified private key using the ECDSA
624
+ * (Elliptic Curve Digital Signature Algorithm) signature algorithm, as defined in RFC6979.
625
+ * The data to be signed is first hashed using the SHA-256 algorithm, and this hash is then
626
+ * signed using the private key. The output is a digital signature in the form of a
627
+ * Uint8Array, which uniquely corresponds to both the data and the private key used for signing.
628
+ *
629
+ * This method is commonly used in cryptographic applications to ensure data integrity and
630
+ * authenticity. The signature can later be verified by parties with access to the corresponding
631
+ * public key, ensuring that the data has not been tampered with and was indeed signed by the
632
+ * holder of the private key.
633
+ *
634
+ * @example
635
+ * ```ts
636
+ * const data = new TextEncoder().encode('Messsage'); // Data to be signed
637
+ * const privateKey = { ... }; // A Jwk object representing a secp256r1 private key
638
+ * const signature = await Secp256r1.sign({
639
+ * key: privateKey,
640
+ * data
641
+ * });
642
+ * ```
643
+ *
644
+ * @param params - The parameters for the signing operation.
645
+ * @param params.key - The private key to use for signing, represented in JWK format.
646
+ * @param params.data - The data to sign, represented as a Uint8Array.
647
+ *
648
+ * @returns A Promise that resolves to the signature as a Uint8Array.
649
+ */
650
+ public static async sign({ data, key }:
651
+ SignParams
652
+ ): Promise<Uint8Array> {
653
+ // Convert the private key from JWK format to bytes.
654
+ const privateKeyBytes = await Secp256r1.privateKeyToBytes({ privateKey: key });
655
+
656
+ // Generate a digest of the data using the SHA-256 hash function.
657
+ const digest = sha256(data);
658
+
659
+ // Sign the provided data using the ECDSA algorithm.
660
+ // The `Secp256r1.sign` operation returns a signature object with { r, s, recovery } properties.
661
+ const signatureObject = secp256r1.sign(digest, privateKeyBytes);
662
+
663
+ // Convert the signature object to Uint8Array.
664
+ const signature = signatureObject.toCompactRawBytes();
665
+
666
+ return signature;
667
+ }
668
+
669
+ /**
670
+ * Validates a given private key to ensure its compliance with the secp256r1 curve standards.
671
+ *
672
+ * @remarks
673
+ * This method checks whether a provided private key is a valid 32-byte number and falls within
674
+ * the range defined by the secp256r1 curve's order. It is essential for ensuring the private
675
+ * key's mathematical correctness in the context of secp256r1-based cryptographic operations.
676
+ *
677
+ * Note that this validation strictly pertains to the key's format and numerical validity; it does
678
+ * not assess whether the key corresponds to a known entity or its security status (e.g., whether
679
+ * it has been compromised).
680
+ *
681
+ * @example
682
+ * ```ts
683
+ * const privateKeyBytes = new Uint8Array([...]); // A 32-byte private key
684
+ * const isValid = await Secp256r1.validatePrivateKey({ privateKeyBytes });
685
+ * console.log(isValid); // true or false based on the key's validity
686
+ * ```
687
+ *
688
+ * @param params - The parameters for the key validation.
689
+ * @param params.privateKeyBytes - The private key to validate, represented as a Uint8Array.
690
+ *
691
+ * @returns A Promise that resolves to a boolean indicating whether the private key is valid.
692
+ */
693
+ public static async validatePrivateKey({ privateKeyBytes }: {
694
+ privateKeyBytes: Uint8Array;
695
+ }): Promise<boolean> {
696
+ return secp256r1.utils.isValidPrivateKey(privateKeyBytes);
697
+ }
698
+
699
+ /**
700
+ * Validates a given public key to confirm its mathematical correctness on the secp256r1 curve.
701
+ *
702
+ * @remarks
703
+ * This method checks if the provided public key represents a valid point on the secp256r1 curve.
704
+ * It decodes the key's Weierstrass points (x and y coordinates) and verifies their validity
705
+ * against the curve's parameters. A valid point must lie on the curve and meet specific
706
+ * mathematical criteria defined by the curve's equation.
707
+ *
708
+ * It's important to note that this method does not verify the key's ownership or whether it has
709
+ * been compromised; it solely focuses on the key's adherence to the curve's mathematical
710
+ * principles.
711
+ *
712
+ * @example
713
+ * ```ts
714
+ * const publicKeyBytes = new Uint8Array([...]); // A public key in byte format
715
+ * const isValid = await Secp256r1.validatePublicKey({ publicKeyBytes });
716
+ * console.log(isValid); // true if the key is valid on the secp256r1 curve, false otherwise
717
+ * ```
718
+ *
719
+ * @param params - The parameters for the key validation.
720
+ * @param params.publicKeyBytes - The public key to validate, represented as a Uint8Array.
721
+ *
722
+ * @returns A Promise that resolves to a boolean indicating the public key's validity on
723
+ * the secp256r1 curve.
724
+ */
725
+ public static async validatePublicKey({ publicKeyBytes }: {
726
+ publicKeyBytes: Uint8Array;
727
+ }): Promise<boolean> {
728
+ try {
729
+ // Decode Weierstrass points from key bytes.
730
+ const point = secp256r1.ProjectivePoint.fromHex(publicKeyBytes);
731
+
732
+ // Check if points are on the Short Weierstrass curve.
733
+ point.assertValidity();
734
+
735
+ } catch(error: any) {
736
+ return false;
737
+ }
738
+
739
+ return true;
740
+ }
741
+
742
+ /**
743
+ * Verifies an RFC6979-compliant ECDSA signature against given data and a secp256r1 public key.
744
+ *
745
+ * @remarks
746
+ * This method validates a digital signature to ensure that it was generated by the holder of the
747
+ * corresponding private key and that the signed data has not been altered. The signature
748
+ * verification is performed using the ECDSA (Elliptic Curve Digital Signature Algorithm) as
749
+ * specified in RFC6979. The data to be verified is first hashed using the SHA-256 algorithm, and
750
+ * this hash is then used along with the public key to verify the signature.
751
+ *
752
+ * The method returns a boolean value indicating whether the signature is valid. A valid signature
753
+ * proves that the signed data was indeed signed by the owner of the private key corresponding to
754
+ * the provided public key and that the data has not been tampered with since it was signed.
755
+ *
756
+ * Note: The verification process does not consider the malleability of low-s signatures, which
757
+ * may be relevant in certain contexts, such as Bitcoin transactions.
758
+ *
759
+ * @example
760
+ * ```ts
761
+ * const data = new TextEncoder().encode('Messsage'); // Data that was signed
762
+ * const publicKey = { ... }; // Public key in JWK format corresponding to the private key that signed the data
763
+ * const signature = new Uint8Array([...]); // Signature to verify
764
+ * const isSignatureValid = await Secp256r1.verify({
765
+ * key: publicKey,
766
+ * signature,
767
+ * data
768
+ * });
769
+ * console.log(isSignatureValid); // true if the signature is valid, false otherwise
770
+ * ```
771
+ *
772
+ * @param params - The parameters for the signature verification.
773
+ * @param params.key - The public key used for verification, represented in JWK format.
774
+ * @param params.signature - The signature to verify, represented as a Uint8Array.
775
+ * @param params.data - The data that was signed, represented as a Uint8Array.
776
+ *
777
+ * @returns A Promise that resolves to a boolean indicating whether the signature is valid.
778
+ */
779
+ public static async verify({ key, signature, data }:
780
+ VerifyParams
781
+ ): Promise<boolean> {
782
+ // Convert the public key from JWK format to bytes.
783
+ const publicKeyBytes = await Secp256r1.publicKeyToBytes({ publicKey: key });
784
+
785
+ // Generate a digest of the data using the SHA-256 hash function.
786
+ const digest = sha256(data);
787
+
788
+ /** Perform the verification of the signature.
789
+ * This verify operation has the malleability check disabled. Guaranteed support
790
+ * for low-s signatures across languages is unlikely especially in the context
791
+ * of SSI. Notable Cloud KMS providers do not natively support it either. It is
792
+ * also worth noting that low-s signatures are a requirement for Bitcoin. */
793
+ const isValid = secp256r1.verify(signature, digest, publicKeyBytes, { lowS: false });
794
+
795
+ return isValid;
796
+ }
797
+
798
+ /**
799
+ * Returns the elliptic curve point (x and y coordinates) for a given secp256r1 key.
800
+ *
801
+ * @remarks
802
+ * This method extracts the elliptic curve point from a given secp256r1 key, whether
803
+ * it's a private or a public key. For a private key, the method first computes the
804
+ * corresponding public key and then extracts the x and y coordinates. For a public key,
805
+ * it directly returns these coordinates. The coordinates are represented as Uint8Array.
806
+ *
807
+ * The x and y coordinates represent the key's position on the elliptic curve and can be
808
+ * used in various cryptographic operations, such as digital signatures or key agreement
809
+ * protocols.
810
+ *
811
+ * @example
812
+ * ```ts
813
+ * // For a private key
814
+ * const privateKey = new Uint8Array([...]); // A 32-byte private key
815
+ * const { x: xFromPrivateKey, y: yFromPrivateKey } = await Secp256r1.getCurvePoint({ keyBytes: privateKey });
816
+ *
817
+ * // For a public key
818
+ * const publicKey = new Uint8Array([...]); // A 33-byte or 65-byte public key
819
+ * const { x: xFromPublicKey, y: yFromPublicKey } = await Secp256r1.getCurvePoint({ keyBytes: publicKey });
820
+ * ```
821
+ *
822
+ * @param params - The parameters for the curve point decoding operation.
823
+ * @param params.keyBytes - The key for which to get the elliptic curve point.
824
+ * Can be either a private key or a public key.
825
+ * The key should be passed as a `Uint8Array`.
826
+ *
827
+ * @returns A Promise that resolves to an object with properties 'x' and 'y',
828
+ * each being a Uint8Array representing the x and y coordinates of the key point on the
829
+ * elliptic curve.
830
+ */
831
+ private static async getCurvePoint({ keyBytes }: {
832
+ keyBytes: Uint8Array;
833
+ }): Promise<AffinePoint<Uint8Array>> {
834
+ // If key is a private key, first compute the public key.
835
+ if (keyBytes.byteLength === 32) {
836
+ keyBytes = secp256r1.getPublicKey(keyBytes);
837
+ }
838
+
839
+ // Decode Weierstrass affine point from key bytes.
840
+ const point = secp256r1.ProjectivePoint.fromHex(keyBytes);
841
+
842
+ // Get x- and y-coordinate values and convert to Uint8Array.
843
+ const x = numberToBytesBE(point.x, 32);
844
+ const y = numberToBytesBE(point.y, 32);
845
+
846
+ return { x, y };
847
+ }
848
+ }
849
+
850
+ export { Secp256r1 as P256 };