import * as crypto from 'crypto';

const ALGORITHM = 'aes-256-gcm';
const IV_LENGTH = 12;
const TAG_LENGTH = 16;

/**
 * [CORE_SEC_01] 凭证保险库加密内核
 * 使用 AES-256-GCM 确保数据的保密性与完整性
 */
export class VaultCrypto {
  private static MASTER_KEY = process.env.VAULT_MASTER_KEY || 'crawlful_default_master_key_32chars_';

  /**
   * 加密
   */
  static encrypt(text: string, key: string = this.MASTER_KEY): { encryptedData: string; iv: string; tag: string } {
    const iv = crypto.randomBytes(IV_LENGTH);
    const cipher = crypto.createCipheriv(ALGORITHM, Buffer.from(key.padEnd(32).substring(0, 32)), iv);
    
    let encrypted = cipher.update(text, 'utf8', 'hex');
    encrypted += cipher.final('hex');
    
    const tag = cipher.getAuthTag();

    return {
      encryptedData: encrypted,
      iv: iv.toString('base64'),
      tag: tag.toString('base64'),
    };
  }

  /**
   * 解密
   */
  static decrypt(encryptedData: string, iv: string, tag: string, key: string = this.MASTER_KEY): string {
    const decipher = crypto.createDecipheriv(
      ALGORITHM,
      Buffer.from(key.padEnd(32).substring(0, 32)),
      Buffer.from(iv, 'base64')
    );
    
    decipher.setAuthTag(Buffer.from(tag, 'base64'));
    
    let decrypted = decipher.update(encryptedData, 'hex', 'utf8');
    decrypted += decipher.final('utf8');
    
    return decrypted;
  }
}
