@digitaldefiance/ecies-lib 4.5.18 → 4.6.0

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 (63) hide show
  1. package/package.json +1 -1
  2. package/src/constants.d.ts +7 -0
  3. package/src/constants.d.ts.map +1 -1
  4. package/src/constants.js +25 -1
  5. package/src/constants.js.map +1 -1
  6. package/src/enumerations/index.d.ts +1 -0
  7. package/src/enumerations/index.d.ts.map +1 -1
  8. package/src/enumerations/index.js +1 -0
  9. package/src/enumerations/index.js.map +1 -1
  10. package/src/enumerations/voting-error-type.d.ts +37 -0
  11. package/src/enumerations/voting-error-type.d.ts.map +1 -0
  12. package/src/enumerations/voting-error-type.js +48 -0
  13. package/src/enumerations/voting-error-type.js.map +1 -0
  14. package/src/errors/index.d.ts +1 -0
  15. package/src/errors/index.d.ts.map +1 -1
  16. package/src/errors/index.js +1 -0
  17. package/src/errors/index.js.map +1 -1
  18. package/src/errors/voting.d.ts +16 -0
  19. package/src/errors/voting.d.ts.map +1 -0
  20. package/src/errors/voting.js +25 -0
  21. package/src/errors/voting.js.map +1 -0
  22. package/src/index.d.ts +2 -0
  23. package/src/index.d.ts.map +1 -1
  24. package/src/index.js +2 -0
  25. package/src/index.js.map +1 -1
  26. package/src/interfaces/constants.d.ts +2 -0
  27. package/src/interfaces/constants.d.ts.map +1 -1
  28. package/src/interfaces/ecies-library.d.ts +260 -0
  29. package/src/interfaces/ecies-library.d.ts.map +1 -0
  30. package/src/interfaces/ecies-library.js +9 -0
  31. package/src/interfaces/ecies-library.js.map +1 -0
  32. package/src/interfaces/index.d.ts +3 -0
  33. package/src/interfaces/index.d.ts.map +1 -1
  34. package/src/interfaces/index.js +3 -0
  35. package/src/interfaces/index.js.map +1 -1
  36. package/src/interfaces/platform-buffer.d.ts +9 -0
  37. package/src/interfaces/platform-buffer.d.ts.map +1 -0
  38. package/src/interfaces/platform-buffer.js +3 -0
  39. package/src/interfaces/platform-buffer.js.map +1 -0
  40. package/src/interfaces/voting-consts.d.ts +82 -0
  41. package/src/interfaces/voting-consts.d.ts.map +1 -0
  42. package/src/interfaces/voting-consts.js +3 -0
  43. package/src/interfaces/voting-consts.js.map +1 -0
  44. package/src/interfaces/voting-service.d.ts +172 -0
  45. package/src/interfaces/voting-service.d.ts.map +1 -0
  46. package/src/interfaces/voting-service.js +10 -0
  47. package/src/interfaces/voting-service.js.map +1 -0
  48. package/src/isolated-private.d.ts +61 -0
  49. package/src/isolated-private.d.ts.map +1 -0
  50. package/src/isolated-private.js +148 -0
  51. package/src/isolated-private.js.map +1 -0
  52. package/src/isolated-public.d.ts +117 -0
  53. package/src/isolated-public.d.ts.map +1 -0
  54. package/src/isolated-public.js +334 -0
  55. package/src/isolated-public.js.map +1 -0
  56. package/src/services/index.d.ts +1 -1
  57. package/src/services/index.d.ts.map +1 -1
  58. package/src/services/index.js +1 -11
  59. package/src/services/index.js.map +1 -1
  60. package/src/services/voting.service.d.ts +32 -2
  61. package/src/services/voting.service.d.ts.map +1 -1
  62. package/src/services/voting.service.js +230 -27
  63. package/src/services/voting.service.js.map +1 -1
@@ -0,0 +1,61 @@
1
+ import { PrivateKey } from 'paillier-bigint';
2
+ import { IsolatedPublicKey } from './isolated-public';
3
+ /**
4
+ * IsolatedPrivateKey extends Paillier PrivateKey with instance isolation validation.
5
+ *
6
+ * This class ensures that:
7
+ * - Decryption only works with ciphertexts encrypted by the matching IsolatedPublicKey instance
8
+ * - Instance ID verification prevents cross-instance decryption attacks
9
+ * - HMAC validation ensures ciphertext integrity
10
+ *
11
+ * The private key stores the original keyId and instanceId from construction time,
12
+ * and validates them before any decryption operation.
13
+ */
14
+ export declare class IsolatedPrivateKey extends PrivateKey {
15
+ /**
16
+ * Original keyId from the IsolatedPublicKey at construction time
17
+ */
18
+ private readonly _originalKeyId;
19
+ /**
20
+ * Original instanceId from the IsolatedPublicKey at construction time
21
+ */
22
+ private readonly _originalInstanceId;
23
+ /**
24
+ * Reference to the original IsolatedPublicKey
25
+ */
26
+ private readonly _originalPublicKey;
27
+ constructor(lambda: bigint, mu: bigint, publicKey: IsolatedPublicKey);
28
+ /**
29
+ * Converts hex string to Uint8Array
30
+ */
31
+ private hexToUint8Array;
32
+ /**
33
+ * Converts Uint8Array to hex string
34
+ */
35
+ private uint8ArrayToHex;
36
+ /**
37
+ * Compares two Uint8Arrays for equality
38
+ */
39
+ private uint8ArrayEquals;
40
+ /**
41
+ * Decrypts a tagged ciphertext after validating instance ID and HMAC
42
+ */
43
+ decryptAsync(taggedCiphertext: bigint): Promise<bigint>;
44
+ /**
45
+ * Synchronous decrypt override (throws error - use decryptAsync instead)
46
+ */
47
+ decrypt(_taggedCiphertext: bigint): bigint;
48
+ /**
49
+ * Gets a copy of the original keyId
50
+ */
51
+ getOriginalKeyId(): Uint8Array;
52
+ /**
53
+ * Gets a copy of the original instanceId
54
+ */
55
+ getOriginalInstanceId(): Uint8Array;
56
+ /**
57
+ * Gets the original public key reference
58
+ */
59
+ getOriginalPublicKey(): IsolatedPublicKey;
60
+ }
61
+ //# sourceMappingURL=isolated-private.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"isolated-private.d.ts","sourceRoot":"","sources":["../../../../packages/digitaldefiance-ecies-lib/src/isolated-private.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAa,MAAM,iBAAiB,CAAC;AAIxD,OAAO,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AAEtD;;;;;;;;;;GAUG;AACH,qBAAa,kBAAmB,SAAQ,UAAU;IAChD;;OAEG;IACH,OAAO,CAAC,QAAQ,CAAC,cAAc,CAAa;IAE5C;;OAEG;IACH,OAAO,CAAC,QAAQ,CAAC,mBAAmB,CAAa;IAEjD;;OAEG;IACH,OAAO,CAAC,QAAQ,CAAC,kBAAkB,CAAoB;gBAE3C,MAAM,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,SAAS,EAAE,iBAAiB;IAepE;;OAEG;IACH,OAAO,CAAC,eAAe;IAWvB;;OAEG;IACH,OAAO,CAAC,eAAe;IAMvB;;OAEG;IACH,OAAO,CAAC,gBAAgB;IAQxB;;OAEG;IACU,YAAY,CAAC,gBAAgB,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IAiEpE;;OAEG;IACM,OAAO,CAAC,iBAAiB,EAAE,MAAM,GAAG,MAAM;IAInD;;OAEG;IACI,gBAAgB,IAAI,UAAU;IAIrC;;OAEG;IACI,qBAAqB,IAAI,UAAU;IAI1C;;OAEG;IACI,oBAAoB,IAAI,iBAAiB;CAGjD"}
@@ -0,0 +1,148 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.IsolatedPrivateKey = void 0;
4
+ const paillier_bigint_1 = require("paillier-bigint");
5
+ const constants_1 = require("./constants");
6
+ const voting_error_type_1 = require("./enumerations/voting-error-type");
7
+ const voting_1 = require("./errors/voting");
8
+ const isolated_public_1 = require("./isolated-public");
9
+ /**
10
+ * IsolatedPrivateKey extends Paillier PrivateKey with instance isolation validation.
11
+ *
12
+ * This class ensures that:
13
+ * - Decryption only works with ciphertexts encrypted by the matching IsolatedPublicKey instance
14
+ * - Instance ID verification prevents cross-instance decryption attacks
15
+ * - HMAC validation ensures ciphertext integrity
16
+ *
17
+ * The private key stores the original keyId and instanceId from construction time,
18
+ * and validates them before any decryption operation.
19
+ */
20
+ class IsolatedPrivateKey extends paillier_bigint_1.PrivateKey {
21
+ /**
22
+ * Original keyId from the IsolatedPublicKey at construction time
23
+ */
24
+ _originalKeyId;
25
+ /**
26
+ * Original instanceId from the IsolatedPublicKey at construction time
27
+ */
28
+ _originalInstanceId;
29
+ /**
30
+ * Reference to the original IsolatedPublicKey
31
+ */
32
+ _originalPublicKey;
33
+ constructor(lambda, mu, publicKey) {
34
+ if (!isolated_public_1.IsolatedPublicKey.isIsolatedPublicKey(publicKey)) {
35
+ throw new voting_1.VotingError(voting_error_type_1.VotingErrorType.InvalidPublicKeyFormat);
36
+ }
37
+ // Create a base PublicKey instance for the parent constructor
38
+ const basePublicKey = new paillier_bigint_1.PublicKey(publicKey.n, publicKey.g);
39
+ super(lambda, mu, basePublicKey);
40
+ // Store the isolated public key for our own use
41
+ this._originalKeyId = publicKey.getKeyId();
42
+ this._originalInstanceId = publicKey.getInstanceId();
43
+ this._originalPublicKey = publicKey;
44
+ }
45
+ /**
46
+ * Converts hex string to Uint8Array
47
+ */
48
+ hexToUint8Array(hex) {
49
+ if (hex.length % 2 !== 0) {
50
+ hex = '0' + hex;
51
+ }
52
+ const bytes = new Uint8Array(hex.length / 2);
53
+ for (let i = 0; i < hex.length; i += 2) {
54
+ bytes[i / 2] = parseInt(hex.substr(i, 2), 16);
55
+ }
56
+ return bytes;
57
+ }
58
+ /**
59
+ * Converts Uint8Array to hex string
60
+ */
61
+ uint8ArrayToHex(bytes) {
62
+ return Array.from(bytes)
63
+ .map((b) => b.toString(16).padStart(2, '0'))
64
+ .join('');
65
+ }
66
+ /**
67
+ * Compares two Uint8Arrays for equality
68
+ */
69
+ uint8ArrayEquals(a, b) {
70
+ if (a.length !== b.length)
71
+ return false;
72
+ for (let i = 0; i < a.length; i++) {
73
+ if (a[i] !== b[i])
74
+ return false;
75
+ }
76
+ return true;
77
+ }
78
+ /**
79
+ * Decrypts a tagged ciphertext after validating instance ID and HMAC
80
+ */
81
+ async decryptAsync(taggedCiphertext) {
82
+ // First verify if we're using a recovered key by checking the public key instance
83
+ if (!isolated_public_1.IsolatedPublicKey.isIsolatedPublicKey(this._originalPublicKey)) {
84
+ throw new voting_1.VotingError(voting_error_type_1.VotingErrorType.InvalidPublicKeyFormat);
85
+ }
86
+ // Compare instance IDs before any ciphertext operations
87
+ const currentInstanceId = this._originalPublicKey.getInstanceId();
88
+ // This check must happen before any ciphertext operations
89
+ if (!this.uint8ArrayEquals(currentInstanceId, this._originalInstanceId)) {
90
+ throw new voting_1.VotingError(voting_error_type_1.VotingErrorType.InstanceIdMismatch);
91
+ }
92
+ // Now that we've verified the instance ID, we can proceed with ciphertext operations
93
+ try {
94
+ const hmacLength = 64;
95
+ const ciphertextString = taggedCiphertext.toString(constants_1.VOTING.KEY_RADIX);
96
+ const receivedHmac = ciphertextString.slice(-hmacLength);
97
+ const ciphertextHex = ciphertextString.slice(0, -hmacLength);
98
+ const ciphertextBigInt = BigInt(`0x${ciphertextHex}`);
99
+ // Create HMAC key from originalKeyId + originalInstanceId
100
+ const hmacKeyMaterial = new Uint8Array(this._originalKeyId.length + this._originalInstanceId.length);
101
+ hmacKeyMaterial.set(this._originalKeyId, 0);
102
+ hmacKeyMaterial.set(this._originalInstanceId, this._originalKeyId.length);
103
+ const hmacKey = await crypto.subtle.importKey('raw', hmacKeyMaterial, { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
104
+ // Calculate expected HMAC
105
+ const ciphertextBytes = new TextEncoder().encode(ciphertextBigInt.toString(constants_1.VOTING.KEY_RADIX));
106
+ const signature = await crypto.subtle.sign('HMAC', hmacKey, ciphertextBytes);
107
+ const expectedHmac = this.uint8ArrayToHex(new Uint8Array(signature));
108
+ // Verify HMAC
109
+ if (receivedHmac !== expectedHmac) {
110
+ throw new voting_1.VotingError(voting_error_type_1.VotingErrorType.InvalidCiphertextHmac);
111
+ }
112
+ // Finally decrypt the ciphertext using the parent class implementation
113
+ return super.decrypt(ciphertextBigInt);
114
+ }
115
+ catch (error) {
116
+ if (error instanceof voting_1.VotingError) {
117
+ throw error;
118
+ }
119
+ throw new voting_1.VotingError(voting_error_type_1.VotingErrorType.InvalidPrivateKeyBufferFailedToParse);
120
+ }
121
+ }
122
+ /**
123
+ * Synchronous decrypt override (throws error - use decryptAsync instead)
124
+ */
125
+ decrypt(_taggedCiphertext) {
126
+ throw new voting_1.VotingError(voting_error_type_1.VotingErrorType.KeyPairValidationFailed);
127
+ }
128
+ /**
129
+ * Gets a copy of the original keyId
130
+ */
131
+ getOriginalKeyId() {
132
+ return new Uint8Array(this._originalKeyId);
133
+ }
134
+ /**
135
+ * Gets a copy of the original instanceId
136
+ */
137
+ getOriginalInstanceId() {
138
+ return new Uint8Array(this._originalInstanceId);
139
+ }
140
+ /**
141
+ * Gets the original public key reference
142
+ */
143
+ getOriginalPublicKey() {
144
+ return this._originalPublicKey;
145
+ }
146
+ }
147
+ exports.IsolatedPrivateKey = IsolatedPrivateKey;
148
+ //# sourceMappingURL=isolated-private.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"isolated-private.js","sourceRoot":"","sources":["../../../../packages/digitaldefiance-ecies-lib/src/isolated-private.ts"],"names":[],"mappings":";;;AAAA,qDAAwD;AACxD,2CAAqC;AACrC,wEAAmE;AACnE,4CAA8C;AAC9C,uDAAsD;AAEtD;;;;;;;;;;GAUG;AACH,MAAa,kBAAmB,SAAQ,4BAAU;IAChD;;OAEG;IACc,cAAc,CAAa;IAE5C;;OAEG;IACc,mBAAmB,CAAa;IAEjD;;OAEG;IACc,kBAAkB,CAAoB;IAEvD,YAAY,MAAc,EAAE,EAAU,EAAE,SAA4B;QAClE,IAAI,CAAC,mCAAiB,CAAC,mBAAmB,CAAC,SAAS,CAAC,EAAE,CAAC;YACtD,MAAM,IAAI,oBAAW,CAAC,mCAAe,CAAC,sBAAsB,CAAC,CAAC;QAChE,CAAC;QAED,8DAA8D;QAC9D,MAAM,aAAa,GAAG,IAAI,2BAAS,CAAC,SAAS,CAAC,CAAC,EAAE,SAAS,CAAC,CAAC,CAAC,CAAC;QAC9D,KAAK,CAAC,MAAM,EAAE,EAAE,EAAE,aAAa,CAAC,CAAC;QAEjC,gDAAgD;QAChD,IAAI,CAAC,cAAc,GAAG,SAAS,CAAC,QAAQ,EAAE,CAAC;QAC3C,IAAI,CAAC,mBAAmB,GAAG,SAAS,CAAC,aAAa,EAAE,CAAC;QACrD,IAAI,CAAC,kBAAkB,GAAG,SAAS,CAAC;IACtC,CAAC;IAED;;OAEG;IACK,eAAe,CAAC,GAAW;QACjC,IAAI,GAAG,CAAC,MAAM,GAAG,CAAC,K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PublicKey extends Paillier PublicKey with instance isolation capabilities.
4
+ *
5
+ * This class provides:
6
+ * - keyId: A deterministic SHA-256 hash of the public key 'n' value for verification
7
+ * - instanceId: A unique identifier per key instance to prevent cross-instance operations
8
+ * - HMAC-tagged ciphertexts that bind encrypted values to a specific key instance
9
+ *
10
+ * Instance isolation ensures that ciphertexts encrypted with one instance cannot be
11
+ * used with another instance, even if they share the same underlying key material.
12
+ * This is critical for voting systems where ballot tampering must be prevented.
13
+ */
14
+ export declare class IsolatedPublicKey extends PublicKey {
15
+ /**
16
+ * Type guard to check if a PublicKey is an IsolatedPublicKey
17
+ */
18
+ static isIsolatedPublicKey(key: PublicKey): key is IsolatedPublicKey;
19
+ /**
20
+ * Deterministic identifier derived from the public key (SHA-256 of 'n')
21
+ */
22
+ readonly keyId: Uint8Array;
23
+ /**
24
+ * Original instance ID generated at construction time
25
+ */
26
+ private readonly _originalInstanceId;
27
+ /**
28
+ * Current instance ID (can be updated via updateInstanceId())
29
+ */
30
+ private _currentInstanceId;
31
+ /**
32
+ * Unique salt used for instance ID generation
33
+ */
34
+ private readonly uniqueInstanceSalt;
35
+ /**
36
+ * Updates the current instance ID to a new random value.
37
+ * This invalidates all previously encrypted ciphertexts.
38
+ */
39
+ updateInstanceId(): Promise<void>;
40
+ /**
41
+ * Generates a deterministic instance ID from keyId, n, and a unique salt
42
+ */
43
+ private generateInstanceId;
44
+ /**
45
+ * Async SHA-256 hash using Web Crypto API
46
+ */
47
+ private sha256Async;
48
+ /**
49
+ * Converts hex string to Uint8Array
50
+ */
51
+ private hexToUint8Array;
52
+ /**
53
+ * Converts Uint8Array to hex string
54
+ */
55
+ private uint8ArrayToHex;
56
+ constructor(n: bigint, g: bigint, keyId: Uint8Array);
57
+ /**
58
+ * Static factory method to create IsolatedPublicKey asynchronously
59
+ */
60
+ static create(n: bigint, g: bigint, keyId: Uint8Array): Promise<IsolatedPublicKey>;
61
+ /**
62
+ * Static factory method to create IsolatedPublicKey from deserialized data
63
+ * Used when reconstructing a key from a buffer with a stored instanceId
64
+ */
65
+ static fromBuffer(n: bigint, g: bigint, keyId: Uint8Array, instanceId: Uint8Array): IsolatedPublicKey;
66
+ /**
67
+ * Returns a copy of the keyId
68
+ */
69
+ getKeyId(): Uint8Array;
70
+ /**
71
+ * Returns a copy of the current instance ID
72
+ */
73
+ getInstanceId(): Uint8Array;
74
+ /**
75
+ * Tags a ciphertext with an HMAC using keyId + instanceId
76
+ * Returns a new bigint with the HMAC appended
77
+ */
78
+ private tagCiphertext;
79
+ /**
80
+ * Extracts and validates the instance ID from a tagged ciphertext
81
+ * Returns the instance ID if valid, or zero-filled array if invalid
82
+ */
83
+ extractInstanceId(ciphertext: bigint): Promise<Uint8Array>;
84
+ /**
85
+ * Encrypts a message and tags it with instance HMAC
86
+ */
87
+ encryptAsync(m: bigint): Promise<bigint>;
88
+ /**
89
+ * Synchronous encrypt override (throws error - use encryptAsync instead)
90
+ */
91
+ encrypt(_m: bigint): bigint;
92
+ /**
93
+ * Multiplies a ciphertext by a constant, preserving instance HMAC
94
+ */
95
+ multiplyAsync(ciphertext: bigint, constant: bigint): Promise<bigint>;
96
+ /**
97
+ * Synchronous multiply override (throws error - use multiplyAsync instead)
98
+ */
99
+ multiply(_ciphertext: bigint, _constant: bigint): bigint;
100
+ /**
101
+ * Adds two ciphertexts, preserving instance HMAC
102
+ */
103
+ additionAsync(a: bigint, b: bigint): Promise<bigint>;
104
+ /**
105
+ * Synchronous addition override (throws error - use additionAsync instead)
106
+ */
107
+ addition(_a: bigint, _b: bigint): bigint;
108
+ /**
109
+ * Verifies that the keyId matches the SHA-256 hash of the public key 'n'
110
+ */
111
+ verifyKeyIdAsync(): Promise<void>;
112
+ /**
113
+ * Compares two Uint8Arrays for equality
114
+ */
115
+ private uint8ArrayEquals;
116
+ }
117
+ //# sourceMappingURL=isolated-public.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"isolated-public.d.ts","sourceRoot":"","sources":["../../../../packages/digitaldefiance-ec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MrD;;OAEG;IACM,OAAO,CAAC,EAAE,EAAE,MAAM,GAAG,MAAM;IAIpC;;OAEG;IACU,aAAa,CACxB,UAAU,EAAE,MAAM,EAClB,QAAQ,EAAE,MAAM,GACf,OAAO,CAAC,MAAM,CAAC;IAmBlB;;OAEG;IACM,QAAQ,CAAC,WAAW,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,MAAM;IAIjE;;OAEG;IACU,aAAa,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IAuBjE;;OAEG;IACM,QAAQ,CAAC,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,GAAG,MAAM;IAIjD;;OAEG;IACU,gBAAgB,IAAI,OAAO,CAAC,IAAI,CAAC;IAc9C;;OAEG;IACH,OAAO,CAAC,gBAAgB;CAOzB"}
@@ -0,0 +1,334 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.IsolatedPublicKey = void 0;
4
+ const paillier_bigint_1 = require("paillier-bigint");
5
+ const constants_1 = require("./constants");
6
+ const voting_error_type_1 = require("./enumerations/voting-error-type");
7
+ const voting_1 = require("./errors/voting");
8
+ /**
9
+ * IsolatedPublicKey extends Paillier PublicKey with instance isolation capabilities.
10
+ *
11
+ * This class provides:
12
+ * - keyId: A deterministic SHA-256 hash of the public key 'n' value for verification
13
+ * - instanceId: A unique identifier per key instance to prevent cross-instance operations
14
+ * - HMAC-tagged ciphertexts that bind encrypted values to a specific key instance
15
+ *
16
+ * Instance isolation ensures that ciphertexts encrypted with one instance cannot be
17
+ * used with another instance, even if they share the same underlying key material.
18
+ * This is critical for voting systems where ballot tampering must be prevented.
19
+ */
20
+ class IsolatedPublicKey extends paillier_bigint_1.PublicKey {
21
+ /**
22
+ * Type guard to check if a PublicKey is an IsolatedPublicKey
23
+ */
24
+ static isIsolatedPublicKey(key) {
25
+ return key instanceof IsolatedPublicKey;
26
+ }
27
+ /**
28
+ * Deterministic identifier derived from the public key (SHA-256 of 'n')
29
+ */
30
+ keyId;
31
+ /**
32
+ * Original instance ID generated at construction time
33
+ */
34
+ _originalInstanceId;
35
+ /**
36
+ * Current instance ID (can be updated via updateInstanceId())
37
+ */
38
+ _currentInstanceId;
39
+ /**
40
+ * Unique salt used for instance ID generation
41
+ */
42
+ uniqueInstanceSalt;
43
+ /**
44
+ * Updates the current instance ID to a new random value.
45
+ * This invalidates all previously encrypted ciphertexts.
46
+ */
47
+ async updateInstanceId() {
48
+ const randomSalt = new Uint8Array(32);
49
+ crypto.getRandomValues(randomSalt);
50
+ this._currentInstanceId = await this.generateInstanceId(this.keyId, this.n, randomSalt);
51
+ }
52
+ /**
53
+ * Generates a deterministic instance ID from keyId, n, and a unique salt
54
+ */
55
+ async generateInstanceId(keyId, n, uniqueInstanceSalt) {
56
+ // Convert n to hex string with proper padding
57
+ const nHex = n
58
+ .toString(constants_1.VOTING.KEY_RADIX)
59
+ .padStart(constants_1.VOTING.PUB_KEY_OFFSET, '0');
60
+ const nBytes = this.hexToUint8Array(nHex);
61
+ // Concatenate keyId + nBytes + salt
62
+ const combined = new Uint8Array(keyId.length + nBytes.length + uniqueInstanceSalt.length);
63
+ combined.set(keyId, 0);
64
+ combined.set(nBytes, keyId.length);
65
+ combined.set(uniqueInstanceSalt, keyId.length + nBytes.length);
66
+ // Return async hash
67
+ return this.sha256Async(combined);
68
+ }
69
+ /**
70
+ * Async SHA-256 hash using Web Crypto API
71
+ */
72
+ async sha256Async(data) {
73
+ const hashBuffer = await crypto.subtle.digest('SHA-256', data);
74
+ return new Uint8Array(hashBuffer);
75
+ }
76
+ /**
77
+ * Converts hex string to Uint8Array
78
+ */
79
+ hexToUint8Array(hex) {
80
+ if (hex.length % 2 !== 0) {
81
+ hex = '0' + hex;
82
+ }
83
+ const bytes = new Uint8Array(hex.length / 2);
84
+ for (let i = 0; i < hex.length; i += 2) {
85
+ bytes[i / 2] = parseInt(hex.substr(i, 2), 16);
86
+ }
87
+ return bytes;
88
+ }
89
+ /**
90
+ * Converts Uint8Array to hex string
91
+ */
92
+ uint8ArrayToHex(bytes) {
93
+ return Array.from(bytes)
94
+ .map((b) => b.toString(16).padStart(2, '0'))
95
+ .join('');
96
+ }
97
+ constructor(n, g, keyId) {
98
+ super(n, g);
99
+ this.keyId = keyId;
100
+ // Generate unique salt for this instance
101
+ const uniqueInstanceSalt = new Uint8Array(32);
102
+ crypto.getRandomValues(uniqueInstanceSalt);
103
+ this.uniqueInstanceSalt = uniqueInstanceSalt;
104
+ // Generate instance IDs (this is problematic with sync constructor)
105
+ // We'll need to handle this differently
106
+ this._originalInstanceId = new Uint8Array(32); // Placeholder
107
+ this._currentInstanceId = new Uint8Array(32); // Placeholder
108
+ // TODO: This needs to be refactored to use async factory method
109
+ }
110
+ /**
111
+ * Static factory method to create IsolatedPublicKey asynchronously
112
+ */
113
+ static async create(n, g, keyId) {
114
+ const key = new IsolatedPublicKey(n, g, keyId);
115
+ // Generate unique salt
116
+ const uniqueInstanceSalt = new Uint8Array(32);
117
+ crypto.getRandomValues(uniqueInstanceSalt);
118
+ // Generate instance ID asynchronously
119
+ const nHex = n
120
+ .toString(constants_1.VOTING.KEY_RADIX)
121
+ .padStart(constants_1.VOTING.PUB_KEY_OFFSET, '0');
122
+ const nBytes = key.hexToUint8Array(nHex);
123
+ const combined = new Uint8Array(keyId.length + nBytes.length + uniqueInstanceSalt.length);
124
+ combined.set(keyId, 0);
125
+ combined.set(nBytes, keyId.length);
126
+ combined.set(uniqueInstanceSalt, keyId.length + nBytes.length);
127
+ const instanceId = await key.sha256Async(combined);
128
+ // Use Object.defineProperty to set readonly fields
129
+ Object.defineProperty(key, 'uniqueInstanceSalt', {
130
+ value: uniqueInstanceSalt,
131
+ writable: false,
132
+ enumerable: true,
133
+ configurable: false,
134
+ });
135
+ Object.defineProperty(key, '_originalInstanceId', {
136
+ value: instanceId,
137
+ writable: false,
138
+ enumerable: false,
139
+ configurable: false,
140
+ });
141
+ Object.defineProperty(key, '_currentInstanceId', {
142
+ value: new Uint8Array(instanceId),
143
+ writable: true,
144
+ enumerable: false,
145
+ configurable: false,
146
+ });
147
+ return key;
148
+ }
149
+ /**
150
+ * Static factory method to create IsolatedPublicKey from deserialized data
151
+ * Used when reconstructing a key from a buffer with a stored instanceId
152
+ */
153
+ static fromBuffer(n, g, keyId, instanceId) {
154
+ const key = new IsolatedPublicKey(n, g, keyId);
155
+ // For deserialized keys, we don't have the original salt
156
+ // Set uniqueInstanceSalt to empty array
157
+ const uniqueInstanceSalt = new Uint8Array(0);
158
+ // Use Object.defineProperty to set readonly fields
159
+ Object.defineProperty(key, 'uniqueInstanceSalt', {
160
+ value: uniqueInstanceSalt,
161
+ writable: false,
162
+ enumerable: true,
163
+ configurable: false,
164
+ });
165
+ Object.defineProperty(key, '_originalInstanceId', {
166
+ value: instanceId,
167
+ writable: false,
168
+ enumerable: false,
169
+ configurable: false,
170
+ });
171
+ Object.defineProperty(key, '_currentInstanceId', {
172
+ value: new Uint8Array(instanceId),
173
+ writable: true,
174
+ enumerable: false,
175
+ configurable: false,
176
+ });
177
+ return key;
178
+ }
179
+ /**
180
+ * Returns a copy of the keyId
181
+ */
182
+ getKeyId() {
183
+ return new Uint8Array(this.keyId);
184
+ }
185
+ /**
186
+ * Returns a copy of the current instance ID
187
+ */
188
+ getInstanceId() {
189
+ return new Uint8Array(this._currentInstanceId);
190
+ }
191
+ /**
192
+ * Tags a ciphertext with an HMAC using keyId + instanceId
193
+ * Returns a new bigint with the HMAC appended
194
+ */
195
+ async tagCiphertext(ciphertext) {
196
+ // Create HMAC key from keyId + instanceId
197
+ const hmacKeyMaterial = new Uint8Array(this.keyId.length + this._currentInstanceId.length);
198
+ hmacKeyMaterial.set(this.keyId, 0);
199
+ hmacKeyMaterial.set(this._currentInstanceId, this.keyId.length);
200
+ // Import HMAC key
201
+ const hmacKey = await crypto.subtle.importKey('raw', hmacKeyMaterial, { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
202
+ // Sign the ciphertext
203
+ const ciphertextHex = ciphertext.toString(constants_1.VOTING.KEY_RADIX);
204
+ const ciphertextBytes = new TextEncoder().encode(ciphertextHex);
205
+ const signature = await crypto.subtle.sign('HMAC', hmacKey, ciphertextBytes);
206
+ const signatureBytes = new Uint8Array(signature);
207
+ const signatureHex = this.uint8ArrayToHex(signatureBytes);
208
+ // Pad ciphertext and append HMAC
209
+ const hmacLength = 64; // 256 bits = 64 hex chars
210
+ const paddedCiphertext = ciphertextHex.padStart(hmacLength * 2, '0');
211
+ const taggedCiphertextString = paddedCiphertext + signatureHex;
212
+ return BigInt(`0x${taggedCiphertextString}`);
213
+ }
214
+ /**
215
+ * Extracts and validates the instance ID from a tagged ciphertext
216
+ * Returns the instance ID if valid, or zero-filled array if invalid
217
+ */
218
+ async extractInstanceId(ciphertext) {
219
+ try {
220
+ const hmacLength = 64;
221
+ const ciphertextString = ciphertext.toString(16);
222
+ const receivedHmac = ciphertextString.slice(-hmacLength);
223
+ const calculatedCiphertext = BigInt(`0x${ciphertextString.slice(0, -hmacLength)}`);
224
+ // Create HMAC key from keyId + current instanceId
225
+ const hmacKeyMaterial = new Uint8Array(this.keyId.length + this._currentInstanceId.length);
226
+ hmacKeyMaterial.set(this.keyId, 0);
227
+ hmacKeyMaterial.set(this._currentInstanceId, this.keyId.length);
228
+ const hmacKey = await crypto.subtle.importKey('raw', hmacKeyMaterial, { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
229
+ // Calculate expected HMAC
230
+ const ciphertextHex = calculatedCiphertext.toString(constants_1.VOTING.KEY_RADIX);
231
+ const ciphertextBytes = new TextEncoder().encode(ciphertextHex);
232
+ const signature = await crypto.subtle.sign('HMAC', hmacKey, ciphertextBytes);
233
+ const expectedHmac = this.uint8ArrayToHex(new Uint8Array(signature));
234
+ // If HMAC matches, return current instance ID
235
+ return receivedHmac === expectedHmac
236
+ ? new Uint8Array(this._currentInstanceId)
237
+ : new Uint8Array([0]);
238
+ }
239
+ catch (_error) {
240
+ // If any error occurs, return invalid instance ID
241
+ return new Uint8Array([0]);
242
+ }
243
+ }
244
+ /**
245
+ * Encrypts a message and tags it with instance HMAC
246
+ */
247
+ async encryptAsync(m) {
248
+ await this.verifyKeyIdAsync();
249
+ const ciphertext = super.encrypt(m);
250
+ return this.tagCiphertext(ciphertext);
251
+ }
252
+ /**
253
+ * Synchronous encrypt override (throws error - use encryptAsync instead)
254
+ */
255
+ encrypt(_m) {
256
+ throw new voting_1.VotingError(voting_error_type_1.VotingErrorType.KeyPairValidationFailed);
257
+ }
258
+ /**
259
+ * Multiplies a ciphertext by a constant, preserving instance HMAC
260
+ */
261
+ async multiplyAsync(ciphertext, constant) {
262
+ await this.verifyKeyIdAsync();
263
+ const instanceId = await this.extractInstanceId(ciphertext);
264
+ // Check if instance IDs match
265
+ if (!this.uint8ArrayEquals(instanceId, this._currentInstanceId)) {
266
+ throw new voting_1.VotingError(voting_error_type_1.VotingErrorType.InstanceIdMismatch);
267
+ }
268
+ const hmacLength = 64;
269
+ const ciphertextString = ciphertext.toString(constants_1.VOTING.KEY_RADIX);
270
+ const actualCiphertext = BigInt(`0x${ciphertextString.slice(0, -hmacLength)}`);
271
+ const product = super.multiply(actualCiphertext, constant);
272
+ return this.tagCiphertext(product);
273
+ }
274
+ /**
275
+ * Synchronous multiply override (throws error - use multiplyAsync instead)
276
+ */
277
+ multiply(_ciphertext, _constant) {
278
+ throw new voting_1.VotingError(voting_error_type_1.VotingErrorType.KeyPairValidationFailed);
279
+ }
280
+ /**
281
+ * Adds two ciphertexts, preserving instance HMAC
282
+ */
283
+ async additionAsync(a, b) {
284
+ await this.verifyKeyIdAsync();
285
+ const aInstanceID = await this.extractInstanceId(a);
286
+ const bInstanceID = await this.extractInstanceId(b);
287
+ if (!this.uint8ArrayEquals(aInstanceID, this._currentInstanceId) ||
288
+ !this.uint8ArrayEquals(bInstanceID, this._currentInstanceId)) {
289
+ throw new voting_1.VotingError(voting_error_type_1.VotingErrorType.InstanceIdMismatch);
290
+ }
291
+ const hmacLength = 64;
292
+ const aCiphertextString = a.toString(constants_1.VOTING.KEY_RADIX);
293
+ const bCiphertextString = b.toString(constants_1.VOTING.KEY_RADIX);
294
+ const aCiphertext = BigInt(`0x${aCiphertextString.slice(0, -hmacLength)}`);
295
+ const bCiphertext = BigInt(`0x${bCiphertextString.slice(0, -hmacLength)}`);
296
+ const sum = super.addition(aCiphertext, bCiphertext);
297
+ return this.tagCiphertext(sum);
298
+ }
299
+ /**
300
+ * Synchronous addition override (throws error - use additionAsync instead)
301
+ */
302
+ addition(_a, _b) {
303
+ throw new voting_1.VotingError(voting_error_type_1.VotingErrorType.KeyPairValidationFailed);
304
+ }
305
+ /**
306
+ * Verifies that the keyId matches the SHA-256 hash of the public key 'n'
307
+ */
308
+ async verifyKeyIdAsync() {
309
+ const nHex = this.n
310
+ .toString(constants_1.VOTING.KEY_RADIX)
311
+ .padStart(constants_1.VOTING.PUB_KEY_OFFSET, '0');
312
+ // Encode the hex string as UTF-8 bytes (not parse as hex digits)
313
+ const encoder = new TextEncoder();
314
+ const nBytes = encoder.encode(nHex);
315
+ const computedKeyId = await this.sha256Async(nBytes);
316
+ if (!this.uint8ArrayEquals(this.keyId, computedKeyId)) {
317
+ throw new voting_1.VotingError(voting_error_type_1.VotingErrorType.InvalidPublicKeyIdMismatch);
318
+ }
319
+ }
320
+ /**
321
+ * Compares two Uint8Arrays for equality
322
+ */
323
+ uint8ArrayEquals(a, b) {
324
+ if (a.length !== b.length)
325
+ return false;
326
+ for (let i = 0; i < a.length; i++) {
327
+ if (a[i] !== b[i])
328
+ return false;
329
+ }
330
+ return true;
331
+ }
332
+ }
333
+ exports.IsolatedPublicKey = IsolatedPublicKey;
334
+ //# sourceMappingURL=isolated-public.js.map