@dimzxzzx07/file-watcher 1.0.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 (100) hide show
  1. package/.env +13 -0
  2. package/.eslintrc.json +128 -0
  3. package/.prettierrc +18 -0
  4. package/Dimzxzzx07.png +0 -0
  5. package/README.md +1024 -0
  6. package/dist/core/BackupManager.d.ts +25 -0
  7. package/dist/core/BackupManager.d.ts.map +1 -0
  8. package/dist/core/BackupManager.js +290 -0
  9. package/dist/core/BackupManager.js.map +1 -0
  10. package/dist/core/IntegrityValidator.d.ts +18 -0
  11. package/dist/core/IntegrityValidator.d.ts.map +1 -0
  12. package/dist/core/IntegrityValidator.js +212 -0
  13. package/dist/core/IntegrityValidator.js.map +1 -0
  14. package/dist/core/SecurityManager.d.ts +40 -0
  15. package/dist/core/SecurityManager.d.ts.map +1 -0
  16. package/dist/core/SecurityManager.js +320 -0
  17. package/dist/core/SecurityManager.js.map +1 -0
  18. package/dist/core/WatcherEngine.d.ts +44 -0
  19. package/dist/core/WatcherEngine.d.ts.map +1 -0
  20. package/dist/core/WatcherEngine.js +470 -0
  21. package/dist/core/WatcherEngine.js.map +1 -0
  22. package/dist/crypto/HashGenerator.d.ts +26 -0
  23. package/dist/crypto/HashGenerator.d.ts.map +1 -0
  24. package/dist/crypto/HashGenerator.js +220 -0
  25. package/dist/crypto/HashGenerator.js.map +1 -0
  26. package/dist/crypto/KeyManager.d.ts +30 -0
  27. package/dist/crypto/KeyManager.d.ts.map +1 -0
  28. package/dist/crypto/KeyManager.js +235 -0
  29. package/dist/crypto/KeyManager.js.map +1 -0
  30. package/dist/crypto/SignatureValidator.d.ts +11 -0
  31. package/dist/crypto/SignatureValidator.d.ts.map +1 -0
  32. package/dist/crypto/SignatureValidator.js +102 -0
  33. package/dist/crypto/SignatureValidator.js.map +1 -0
  34. package/dist/detectors/AnomalyDetector.d.ts +24 -0
  35. package/dist/detectors/AnomalyDetector.d.ts.map +1 -0
  36. package/dist/detectors/AnomalyDetector.js +209 -0
  37. package/dist/detectors/AnomalyDetector.js.map +1 -0
  38. package/dist/detectors/InjectionDetector.d.ts +14 -0
  39. package/dist/detectors/InjectionDetector.d.ts.map +1 -0
  40. package/dist/detectors/InjectionDetector.js +204 -0
  41. package/dist/detectors/InjectionDetector.js.map +1 -0
  42. package/dist/detectors/PatternMatcher.d.ts +28 -0
  43. package/dist/detectors/PatternMatcher.d.ts.map +1 -0
  44. package/dist/detectors/PatternMatcher.js +283 -0
  45. package/dist/detectors/PatternMatcher.js.map +1 -0
  46. package/dist/guards/FileGuard.d.ts +35 -0
  47. package/dist/guards/FileGuard.d.ts.map +1 -0
  48. package/dist/guards/FileGuard.js +357 -0
  49. package/dist/guards/FileGuard.js.map +1 -0
  50. package/dist/guards/MemoryGuard.d.ts +28 -0
  51. package/dist/guards/MemoryGuard.d.ts.map +1 -0
  52. package/dist/guards/MemoryGuard.js +256 -0
  53. package/dist/guards/MemoryGuard.js.map +1 -0
  54. package/dist/guards/ProcessGuard.d.ts +25 -0
  55. package/dist/guards/ProcessGuard.d.ts.map +1 -0
  56. package/dist/guards/ProcessGuard.js +221 -0
  57. package/dist/guards/ProcessGuard.js.map +1 -0
  58. package/dist/index.d.ts +19 -0
  59. package/dist/index.d.ts.map +1 -0
  60. package/dist/index.js +186 -0
  61. package/dist/index.js.map +1 -0
  62. package/dist/types/index.d.ts +69 -0
  63. package/dist/types/index.d.ts.map +1 -0
  64. package/dist/types/index.js +3 -0
  65. package/dist/types/index.js.map +1 -0
  66. package/dist/utils/Constants.d.ts +407 -0
  67. package/dist/utils/Constants.d.ts.map +1 -0
  68. package/dist/utils/Constants.js +505 -0
  69. package/dist/utils/Constants.js.map +1 -0
  70. package/dist/utils/Logger.d.ts +45 -0
  71. package/dist/utils/Logger.d.ts.map +1 -0
  72. package/dist/utils/Logger.js +285 -0
  73. package/dist/utils/Logger.js.map +1 -0
  74. package/dist/utils/Validator.d.ts +27 -0
  75. package/dist/utils/Validator.d.ts.map +1 -0
  76. package/dist/utils/Validator.js +245 -0
  77. package/dist/utils/Validator.js.map +1 -0
  78. package/favicon.png +0 -0
  79. package/jest.config.js +69 -0
  80. package/package.json +69 -0
  81. package/src/core/BackupManager.ts +305 -0
  82. package/src/core/IntegrityValidator.ts +200 -0
  83. package/src/core/SecurityManager.ts +348 -0
  84. package/src/core/WatcherEngine.ts +537 -0
  85. package/src/crypto/HashGenerator.ts +234 -0
  86. package/src/crypto/KeyManager.ts +249 -0
  87. package/src/crypto/SignatureValidator.ts +76 -0
  88. package/src/detectors/AnomalyDetector.ts +247 -0
  89. package/src/detectors/InjectionDetector.ts +233 -0
  90. package/src/detectors/PatternMatcher.ts +319 -0
  91. package/src/guards/FileGuard.ts +385 -0
  92. package/src/guards/MemoryGuard.ts +263 -0
  93. package/src/guards/ProcessGuard.ts +219 -0
  94. package/src/index.ts +189 -0
  95. package/src/types/index.ts +72 -0
  96. package/src/utils/Constants.ts +532 -0
  97. package/src/utils/Logger.ts +279 -0
  98. package/src/utils/Validator.ts +248 -0
  99. package/tests/setup.ts +80 -0
  100. package/tsconfig.json +42 -0
@@ -0,0 +1,234 @@
1
+ import * as crypto from 'crypto';
2
+ import { SecurityConfig } from '../types';
3
+
4
+ export class HashGenerator {
5
+ private readonly config: SecurityConfig;
6
+ private readonly algorithms: string[];
7
+ private readonly salt: Buffer;
8
+
9
+ constructor(config: SecurityConfig) {
10
+ this.config = config;
11
+ this.algorithms = ['sha256', 'sha384', 'sha512', 'blake2b512'];
12
+ this.salt = crypto.randomBytes(32);
13
+ }
14
+
15
+ public generateHash(data: Buffer | string): string {
16
+ const input = typeof data === 'string' ? Buffer.from(data) : data;
17
+
18
+ const hash1 = crypto.createHash(this.config.hashAlgorithm)
19
+ .update(input)
20
+ .update(this.salt)
21
+ .digest('hex');
22
+
23
+ const hash2 = crypto.createHash('blake2b512')
24
+ .update(input)
25
+ .update(hash1)
26
+ .digest('hex');
27
+
28
+ return this.combineHashes([hash1, hash2]);
29
+ }
30
+
31
+ public generateEncryptedHash(data: Buffer | string): string {
32
+ const input = typeof data === 'string' ? Buffer.from(data) : data;
33
+
34
+ const normalHash = this.generateHash(input);
35
+
36
+ const key = crypto.scryptSync(normalHash, this.salt, 32);
37
+ const iv = crypto.randomBytes(16);
38
+
39
+ const cipher = crypto.createCipheriv('aes-256-gcm', key, iv);
40
+ const encrypted = Buffer.concat([
41
+ cipher.update(Buffer.from(normalHash, 'hex')),
42
+ cipher.final()
43
+ ]);
44
+
45
+ const authTag = cipher.getAuthTag();
46
+
47
+ return Buffer.concat([iv, authTag, encrypted]).toString('base64');
48
+ }
49
+
50
+ public generateMultiHash(data: Buffer): string[] {
51
+ const hashes: string[] = [];
52
+
53
+ for (const algorithm of this.algorithms) {
54
+ const hash = crypto.createHash(algorithm)
55
+ .update(data)
56
+ .update(this.salt)
57
+ .digest('hex');
58
+ hashes.push(hash);
59
+ }
60
+
61
+ return hashes;
62
+ }
63
+
64
+ public generateRollingHash(data: Buffer, chunkSize: number = 1024): string[] {
65
+ const hashes: string[] = [];
66
+
67
+ for (let i = 0; i < data.length; i += chunkSize) {
68
+ const chunk = data.subarray(i, Math.min(i + chunkSize, data.length));
69
+ const hash = crypto.createHash('sha256')
70
+ .update(chunk)
71
+ .digest('hex');
72
+ hashes.push(hash);
73
+ }
74
+
75
+ return hashes;
76
+ }
77
+
78
+ public generateMerkleRoot(data: Buffer): string {
79
+ const leaves: string[] = [];
80
+ const chunkSize = 1024;
81
+
82
+ for (let i = 0; i < data.length; i += chunkSize) {
83
+ const chunk = data.subarray(i, Math.min(i + chunkSize, data.length));
84
+ const hash = crypto.createHash('sha256')
85
+ .update(chunk)
86
+ .digest();
87
+ leaves.push(hash.toString('hex'));
88
+ }
89
+
90
+ return this.buildMerkleTree(leaves);
91
+ }
92
+
93
+ private buildMerkleTree(leaves: string[]): string {
94
+ if (leaves.length === 1) {
95
+ return leaves[0] as string;
96
+ }
97
+
98
+ const newLevel: string[] = [];
99
+
100
+ for (let i = 0; i < leaves.length; i += 2) {
101
+ if (i + 1 < leaves.length) {
102
+ const left = leaves[i] as string;
103
+ const right = leaves[i + 1] as string;
104
+ const combined = left + right;
105
+ const hash = crypto.createHash('sha256')
106
+ .update(Buffer.from(combined, 'hex'))
107
+ .digest('hex');
108
+ newLevel.push(hash);
109
+ } else {
110
+ newLevel.push(leaves[i] as string);
111
+ }
112
+ }
113
+
114
+ return this.buildMerkleTree(newLevel);
115
+ }
116
+
117
+ public generateHMAC(data: Buffer | string, key?: Buffer): string {
118
+ const secretKey = key || crypto.randomBytes(32);
119
+ const input = typeof data === 'string' ? Buffer.from(data) : data;
120
+
121
+ const hmac = crypto.createHmac('sha512', secretKey)
122
+ .update(input)
123
+ .digest('hex');
124
+
125
+ return hmac;
126
+ }
127
+
128
+ public generateKeyedHash(data: Buffer, key: Buffer): string {
129
+ const prk = crypto.createHmac('sha256', key)
130
+ .update(data)
131
+ .digest();
132
+
133
+ const okm = crypto.createHmac('sha256', prk)
134
+ .update(Buffer.from([0x01]))
135
+ .digest();
136
+
137
+ return okm.toString('hex');
138
+ }
139
+
140
+ public generateTimeBasedHash(data: Buffer, timestamp: number = Date.now()): string {
141
+ const timeBuffer = Buffer.alloc(8);
142
+ timeBuffer.writeBigUInt64BE(BigInt(timestamp));
143
+
144
+ const combined = Buffer.concat([data, timeBuffer]);
145
+
146
+ return crypto.createHash('sha512')
147
+ .update(combined)
148
+ .update(this.salt)
149
+ .digest('hex');
150
+ }
151
+
152
+ public generateHashChain(data: Buffer, chainLength: number = 10): string[] {
153
+ const chain: string[] = [];
154
+ let current = data;
155
+
156
+ for (let i = 0; i < chainLength; i++) {
157
+ const hash = crypto.createHash('sha256')
158
+ .update(current)
159
+ .digest();
160
+ chain.push(hash.toString('hex'));
161
+ current = hash;
162
+ }
163
+
164
+ return chain;
165
+ }
166
+
167
+ public verifyHashChain(chain: string[]): boolean {
168
+ for (let i = 0; i < chain.length - 1; i++) {
169
+ const hash = crypto.createHash('sha256')
170
+ .update(Buffer.from(chain[i] as string, 'hex'))
171
+ .digest('hex');
172
+
173
+ if (hash !== chain[i + 1]) {
174
+ return false;
175
+ }
176
+ }
177
+
178
+ return true;
179
+ }
180
+
181
+ public generateFingerprint(data: Buffer): string {
182
+ const features = [
183
+ data.length.toString(),
184
+ this.generateHash(data).substring(0, 16),
185
+ this.calculateEntropy(data).toString(),
186
+ this.getFirstBytes(data, 32).toString('hex'),
187
+ this.getLastBytes(data, 32).toString('hex')
188
+ ];
189
+
190
+ return this.generateHash(features.join('|'));
191
+ }
192
+
193
+ private calculateEntropy(data: Buffer): number {
194
+ const frequencies: { [key: number]: number } = {};
195
+
196
+ for (const byte of data) {
197
+ frequencies[byte] = (frequencies[byte] || 0) + 1;
198
+ }
199
+
200
+ let entropy = 0;
201
+ const length = data.length;
202
+
203
+ for (const freq of Object.values(frequencies)) {
204
+ const probability = freq / length;
205
+ entropy -= probability * Math.log2(probability);
206
+ }
207
+
208
+ return entropy;
209
+ }
210
+
211
+ private getFirstBytes(data: Buffer, count: number): Buffer {
212
+ return data.subarray(0, Math.min(count, data.length));
213
+ }
214
+
215
+ private getLastBytes(data: Buffer, count: number): Buffer {
216
+ const start = Math.max(0, data.length - count);
217
+ return data.subarray(start);
218
+ }
219
+
220
+ private combineHashes(hashes: string[]): string {
221
+ const combined = hashes.join('');
222
+ return crypto.createHash('sha512')
223
+ .update(combined)
224
+ .digest('hex');
225
+ }
226
+
227
+ public getSalt(): Buffer {
228
+ return Buffer.from(this.salt);
229
+ }
230
+
231
+ public getAlgorithms(): string[] {
232
+ return [...this.algorithms];
233
+ }
234
+ }
@@ -0,0 +1,249 @@
1
+ import * as crypto from 'crypto';
2
+ import * as fs from 'fs/promises';
3
+ import * as path from 'path';
4
+ import { SecurityConfig } from '../types';
5
+ import { Logger } from '../utils/Logger';
6
+
7
+ export class KeyManager {
8
+ private readonly keys: Map<string, Buffer>;
9
+ private readonly keyDir: string;
10
+ private masterKey: Buffer | null = null;
11
+
12
+ constructor(config: SecurityConfig) {
13
+ this.keys = new Map();
14
+ this.keyDir = path.join(config.watchDir, '.secure', 'keys');
15
+
16
+ this.initializeKeyStorage();
17
+ }
18
+
19
+ private async initializeKeyStorage(): Promise<void> {
20
+ try {
21
+ await fs.mkdir(this.keyDir, { recursive: true, mode: 0o700 });
22
+ await this.loadMasterKey();
23
+ } catch (error) {
24
+ Logger.getInstance().error('Failed to initialize key storage', { error });
25
+ }
26
+ }
27
+
28
+ private async loadMasterKey(): Promise<void> {
29
+ const masterKeyPath = path.join(this.keyDir, 'master.key');
30
+
31
+ try {
32
+ const encryptedKey = await fs.readFile(masterKeyPath);
33
+ this.masterKey = await this.decryptMasterKey(encryptedKey);
34
+ } catch {
35
+ this.masterKey = crypto.randomBytes(32);
36
+ const encryptedKey = await this.encryptMasterKey(this.masterKey);
37
+ await fs.writeFile(masterKeyPath, encryptedKey, { mode: 0o400 });
38
+ }
39
+ }
40
+
41
+ public generateKey(keyId: string, length: number = 32): Buffer {
42
+ const key = crypto.randomBytes(length);
43
+ this.keys.set(keyId, key);
44
+ return key;
45
+ }
46
+
47
+ public async generateKeyPair(keyId: string): Promise<{
48
+ publicKey: Buffer;
49
+ privateKey: Buffer;
50
+ }> {
51
+ const { publicKey, privateKey } = crypto.generateKeyPairSync('rsa', {
52
+ modulusLength: 2048,
53
+ publicKeyEncoding: {
54
+ type: 'spki',
55
+ format: 'der'
56
+ },
57
+ privateKeyEncoding: {
58
+ type: 'pkcs8',
59
+ format: 'der'
60
+ }
61
+ });
62
+
63
+ this.keys.set(`${keyId}_public`, publicKey);
64
+ this.keys.set(`${keyId}_private`, privateKey);
65
+
66
+ await this.saveKeyToDisk(`${keyId}_public`, publicKey);
67
+ await this.saveKeyToDisk(`${keyId}_private`, privateKey);
68
+
69
+ return { publicKey, privateKey };
70
+ }
71
+
72
+ public getKey(keyId: string): Buffer | undefined {
73
+ return this.keys.get(keyId);
74
+ }
75
+
76
+ public async rotateKey(keyId: string): Promise<Buffer> {
77
+ const newKey = this.generateKey(`${keyId}_${Date.now()}`);
78
+ this.keys.set(keyId, newKey);
79
+
80
+ const oldKey = this.keys.get(`${keyId}_old`);
81
+ if (oldKey) {
82
+ await this.archiveKey(keyId, oldKey);
83
+ }
84
+
85
+ return newKey;
86
+ }
87
+
88
+ public async deriveKey(password: string, salt?: Buffer): Promise<Buffer> {
89
+ const useSalt = salt || crypto.randomBytes(16);
90
+
91
+ return new Promise((resolve, reject) => {
92
+ crypto.scrypt(password, useSalt, 32, (err, derivedKey) => {
93
+ if (err) reject(err);
94
+ else resolve(derivedKey);
95
+ });
96
+ });
97
+ }
98
+
99
+ public generateSessionKey(): Buffer {
100
+ return crypto.randomBytes(32);
101
+ }
102
+
103
+ public generateIV(): Buffer {
104
+ return crypto.randomBytes(16);
105
+ }
106
+
107
+ public async encryptWithMasterKey(data: Buffer): Promise<Buffer> {
108
+ if (!this.masterKey) {
109
+ throw new Error('Master key not initialized');
110
+ }
111
+
112
+ const iv = crypto.randomBytes(16);
113
+ const cipher = crypto.createCipheriv('aes-256-gcm', this.masterKey, iv);
114
+
115
+ const encrypted = Buffer.concat([
116
+ cipher.update(data),
117
+ cipher.final()
118
+ ]);
119
+
120
+ const authTag = cipher.getAuthTag();
121
+
122
+ return Buffer.concat([iv, authTag, encrypted]);
123
+ }
124
+
125
+ public async decryptWithMasterKey(encryptedData: Buffer): Promise<Buffer> {
126
+ if (!this.masterKey) {
127
+ throw new Error('Master key not initialized');
128
+ }
129
+
130
+ const iv = encryptedData.subarray(0, 16);
131
+ const authTag = encryptedData.subarray(16, 32);
132
+ const data = encryptedData.subarray(32);
133
+
134
+ const decipher = crypto.createDecipheriv('aes-256-gcm', this.masterKey, iv);
135
+ decipher.setAuthTag(authTag);
136
+
137
+ return Buffer.concat([
138
+ decipher.update(data),
139
+ decipher.final()
140
+ ]);
141
+ }
142
+
143
+ public async signData(keyId: string, data: Buffer): Promise<Buffer> {
144
+ const privateKey = this.keys.get(keyId);
145
+ if (!privateKey) {
146
+ throw new Error(`Key not found: ${keyId}`);
147
+ }
148
+
149
+ const sign = crypto.createSign('RSA-SHA256');
150
+ sign.update(data);
151
+
152
+ return sign.sign({
153
+ key: privateKey,
154
+ format: 'der',
155
+ type: 'pkcs8'
156
+ });
157
+ }
158
+
159
+ public async verifySignature(
160
+ keyId: string,
161
+ data: Buffer,
162
+ signature: Buffer
163
+ ): Promise<boolean> {
164
+ const publicKey = this.keys.get(keyId);
165
+ if (!publicKey) {
166
+ throw new Error(`Key not found: ${keyId}`);
167
+ }
168
+
169
+ const verify = crypto.createVerify('RSA-SHA256');
170
+ verify.update(data);
171
+
172
+ return verify.verify({
173
+ key: publicKey,
174
+ format: 'der',
175
+ type: 'spki'
176
+ }, signature);
177
+ }
178
+
179
+ private async saveKeyToDisk(keyId: string, keyData: Buffer): Promise<void> {
180
+ try {
181
+ const keyPath = path.join(this.keyDir, `${keyId}.key`);
182
+ const encrypted = await this.encryptWithMasterKey(keyData);
183
+ await fs.writeFile(keyPath, encrypted, { mode: 0o400 });
184
+ } catch (error) {
185
+ Logger.getInstance().error(`Failed to save key: ${keyId}`, { error });
186
+ }
187
+ }
188
+
189
+ private async encryptMasterKey(key: Buffer): Promise<Buffer> {
190
+ const platformKey = await this.getPlatformKey();
191
+
192
+ const iv = crypto.randomBytes(16);
193
+ const cipher = crypto.createCipheriv('aes-256-gcm', platformKey, iv);
194
+
195
+ const encrypted = Buffer.concat([
196
+ cipher.update(key),
197
+ cipher.final()
198
+ ]);
199
+
200
+ const authTag = cipher.getAuthTag();
201
+
202
+ return Buffer.concat([iv, authTag, encrypted]);
203
+ }
204
+
205
+ private async decryptMasterKey(encrypted: Buffer): Promise<Buffer> {
206
+ const platformKey = await this.getPlatformKey();
207
+
208
+ const iv = encrypted.subarray(0, 16);
209
+ const authTag = encrypted.subarray(16, 32);
210
+ const data = encrypted.subarray(32);
211
+
212
+ const decipher = crypto.createDecipheriv('aes-256-gcm', platformKey, iv);
213
+ decipher.setAuthTag(authTag);
214
+
215
+ return Buffer.concat([
216
+ decipher.update(data),
217
+ decipher.final()
218
+ ]);
219
+ }
220
+
221
+ private async getPlatformKey(): Promise<Buffer> {
222
+ const platformData = [
223
+ process.platform,
224
+ process.arch,
225
+ process.cwd(),
226
+ __filename,
227
+ process.pid
228
+ ].join('|');
229
+
230
+ return crypto.createHash('sha256').update(platformData).digest();
231
+ }
232
+
233
+ private async archiveKey(keyId: string, keyData: Buffer): Promise<void> {
234
+ const archiveDir = path.join(this.keyDir, 'archive');
235
+ await fs.mkdir(archiveDir, { recursive: true });
236
+
237
+ const archivePath = path.join(archiveDir, `${keyId}_${Date.now()}.key.old`);
238
+ const encrypted = await this.encryptWithMasterKey(keyData);
239
+ await fs.writeFile(archivePath, encrypted, { mode: 0o400 });
240
+ }
241
+
242
+ public getStatus(): any {
243
+ return {
244
+ keyCount: this.keys.size,
245
+ masterKeyInitialized: this.masterKey !== null,
246
+ keyDirectory: this.keyDir
247
+ };
248
+ }
249
+ }
@@ -0,0 +1,76 @@
1
+ import * as crypto from 'crypto';
2
+ import { Logger } from '../utils/Logger';
3
+
4
+ export class SignatureValidator {
5
+ private readonly logger: Logger;
6
+ private readonly keyPair: { publicKey: string; privateKey: string };
7
+
8
+ constructor() {
9
+ this.logger = Logger.getInstance();
10
+
11
+ this.keyPair = this.generateKeyPair();
12
+ }
13
+
14
+ private generateKeyPair(): { publicKey: string; privateKey: string } {
15
+ const { publicKey, privateKey } = crypto.generateKeyPairSync('rsa', {
16
+ modulusLength: 2048,
17
+ publicKeyEncoding: {
18
+ type: 'spki',
19
+ format: 'pem'
20
+ },
21
+ privateKeyEncoding: {
22
+ type: 'pkcs8',
23
+ format: 'pem'
24
+ }
25
+ });
26
+
27
+ return { publicKey, privateKey };
28
+ }
29
+
30
+ public async generateSignature(data: Buffer): Promise<string> {
31
+ try {
32
+ const hash = crypto.createHash('sha512')
33
+ .update(data)
34
+ .digest();
35
+
36
+ const sign = crypto.createSign('RSA-SHA512');
37
+ sign.update(hash);
38
+
39
+ const signature = sign.sign(this.keyPair.privateKey, 'base64');
40
+
41
+ return signature;
42
+ } catch (error) {
43
+ this.logger.error('Failed to generate signature', { error });
44
+ throw error;
45
+ }
46
+ }
47
+
48
+ public async validateSignature(data: Buffer, signature: string): Promise<boolean> {
49
+ try {
50
+ const hash = crypto.createHash('sha512')
51
+ .update(data)
52
+ .digest();
53
+
54
+ const verify = crypto.createVerify('RSA-SHA512');
55
+ verify.update(hash);
56
+
57
+ return verify.verify(this.keyPair.publicKey, signature, 'base64');
58
+ } catch (error) {
59
+ this.logger.error('Failed to validate signature', { error });
60
+ return false;
61
+ }
62
+ }
63
+
64
+ public exportPublicKey(): string {
65
+ return this.keyPair.publicKey;
66
+ }
67
+
68
+ public getStatus(): any {
69
+ return {
70
+ algorithm: 'RSA-SHA512',
71
+ keySize: 2048,
72
+ publicKeyAvailable: !!this.keyPair.publicKey,
73
+ privateKeyAvailable: !!this.keyPair.privateKey
74
+ };
75
+ }
76
+ }