ironGym/webapp/src/utils/encryption.ts
2025-07-03 02:10:40 +03:00

41 lines
1.4 KiB
TypeScript

/**
* @description Utility functions for encrypting and decrypting member IDs
*/
import crypto from 'crypto';
// Secret key for encryption - in production, this should be in environment variables
const ENCRYPTION_KEY = process.env.ENCRYPTION_KEY || 'your-32-character-secret-key-here!';
const ALGORITHM = 'aes-256-cbc';
/**
* Encrypts a member ID
* @param memberId - The member ID to encrypt
* @returns Encrypted string
*/
export function encryptMemberId(memberId: string): string {
const iv = crypto.randomBytes(16);
const cipher = crypto.createCipher(ALGORITHM, ENCRYPTION_KEY);
let encrypted = cipher.update(memberId, 'utf8', 'hex');
encrypted += cipher.final('hex');
return iv.toString('hex') + ':' + encrypted;
}
/**
* Decrypts an encrypted member ID
* @param encryptedMemberId - The encrypted member ID
* @returns Decrypted member ID
*/
export function decryptMemberId(encryptedMemberId: string): string {
try {
const textParts = encryptedMemberId.split(':');
const iv = Buffer.from(textParts.shift()!, 'hex');
const encryptedText = textParts.join(':');
const decipher = crypto.createDecipher(ALGORITHM, ENCRYPTION_KEY);
let decrypted = decipher.update(encryptedText, 'hex', 'utf8');
decrypted += decipher.final('utf8');
return decrypted;
} catch (error) {
throw new Error('Invalid encrypted member ID');
}
}