|
1 | 1 | import crypto from 'crypto';
|
| 2 | +import fs from 'fs'; |
2 | 3 | import { SOURCEBOT_ENCRYPTION_KEY } from './environment';
|
3 | 4 |
|
4 | 5 | const algorithm = 'aes-256-cbc';
|
5 | 6 | const ivLength = 16; // 16 bytes for CBC
|
6 | 7 |
|
| 8 | +const publicKeyCache = new Map<string, string>(); |
| 9 | + |
7 | 10 | const generateIV = (): Buffer => {
|
8 | 11 | return crypto.randomBytes(ivLength);
|
9 | 12 | };
|
@@ -63,3 +66,28 @@ export function decrypt(iv: string, encryptedText: string): string {
|
63 | 66 |
|
64 | 67 | return decrypted;
|
65 | 68 | }
|
| 69 | + |
| 70 | +export function verifySignature(data: string, signature: string, publicKeyPath: string): boolean { |
| 71 | + try { |
| 72 | + let publicKey = publicKeyCache.get(publicKeyPath); |
| 73 | + |
| 74 | + if (!publicKey) { |
| 75 | + if (!fs.existsSync(publicKeyPath)) { |
| 76 | + throw new Error(`Public key file not found at: ${publicKeyPath}`); |
| 77 | + } |
| 78 | + |
| 79 | + publicKey = fs.readFileSync(publicKeyPath, 'utf8'); |
| 80 | + publicKeyCache.set(publicKeyPath, publicKey); |
| 81 | + } |
| 82 | + |
| 83 | + // Convert base64url signature to base64 if needed |
| 84 | + const base64Signature = signature.replace(/-/g, '+').replace(/_/g, '/'); |
| 85 | + const paddedSignature = base64Signature + '='.repeat((4 - base64Signature.length % 4) % 4); |
| 86 | + const signatureBuffer = Buffer.from(paddedSignature, 'base64'); |
| 87 | + |
| 88 | + return crypto.verify(null, Buffer.from(data, 'utf8'), publicKey, signatureBuffer); |
| 89 | + } catch (error) { |
| 90 | + console.error('Error verifying signature:', error); |
| 91 | + return false; |
| 92 | + } |
| 93 | +} |
0 commit comments