Feature: Implemented Secure Merchant Vault Architecture with On-chain segregation and Encryption

This commit is contained in:
mstfyldz
2026-03-12 23:22:52 +03:00
parent b4dff13c94
commit 889eff49c8
5 changed files with 185 additions and 2 deletions

49
lib/encryption.ts Normal file
View File

@@ -0,0 +1,49 @@
import crypto from 'crypto';
const ENCRYPTION_KEY = process.env.ENCRYPTION_SECRET || 'fallback_secret_do_not_use_in_production_12345'; // Must be 32 chars for aes-256-gcm
const IV_LENGTH = 16;
const ALGORITHM = 'aes-256-gcm';
/**
* Encrypts a piece of sensitive text (like a private key)
*/
export function encrypt(text: string): string {
// Ensure key is 32 bytes
const key = crypto.createHash('sha256').update(ENCRYPTION_KEY).digest();
const iv = crypto.randomBytes(IV_LENGTH);
const cipher = crypto.createCipheriv(ALGORITHM, key, iv);
let encrypted = cipher.update(text, 'utf8', 'hex');
encrypted += cipher.final('hex');
const authTag = cipher.getAuthTag().toString('hex');
// Format: iv:authTag:encrypted
return `${iv.toString('hex')}:${authTag}:${encrypted}`;
}
/**
* Decrypts an encrypted string back to its original form
*/
export function decrypt(encryptedText: string): string {
try {
const parts = encryptedText.split(':');
if (parts.length !== 3) throw new Error('Invalid encrypted text format');
const iv = Buffer.from(parts[0], 'hex');
const authTag = Buffer.from(parts[1], 'hex');
const encrypted = parts[2];
const key = crypto.createHash('sha256').update(ENCRYPTION_KEY).digest();
const decipher = crypto.createDecipheriv(ALGORITHM, key, iv);
decipher.setAuthTag(authTag);
let decrypted = decipher.update(encrypted, 'hex', 'utf8');
decrypted += decipher.final('utf8');
return decrypted;
} catch (error) {
console.error('Decryption failed:', error);
throw new Error('Critical: Could not decrypt sensitive data. Check ENCRYPTION_SECRET.');
}
}