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