package com.hikoncont.util

import android.util.Base64
import java.security.MessageDigest
import java.security.SecureRandom
import javax.crypto.Cipher
import javax.crypto.KeyGenerator
import javax.crypto.SecretKey
import javax.crypto.spec.GCMParameterSpec
import javax.crypto.spec.SecretKeySpec

/**
 * 字符串加密工具类
 * 用于保护敏感字符串，防止静态分析
 */
object StringEncryption {
    
    private const val ALGORITHM = "AES"
    private const val TRANSFORMATION = "AES/GCM/NoPadding"
    private const val GCM_IV_LENGTH = 12
    private const val GCM_TAG_LENGTH = 16
    
    // 混淆密钥生成函数
    private fun generateKey(): SecretKey {
        // 使用设备特征生成密钥
        val deviceInfo = android.os.Build.FINGERPRINT + 
                        android.os.Build.SERIAL + 
                        android.os.Build.ID
        
        val digest = MessageDigest.getInstance("SHA-256")
        val keyBytes = digest.digest(deviceInfo.toByteArray())
        
        return SecretKeySpec(keyBytes, ALGORITHM)
    }
    
    /**
     * 加密字符串
     * @param plainText 明文
     * @return Base64编码的密文
     */
    fun encrypt(plainText: String): String {
        try {
            val key = generateKey()
            val cipher = Cipher.getInstance(TRANSFORMATION)
            
            // 生成随机IV
            val iv = ByteArray(GCM_IV_LENGTH)
            SecureRandom().nextBytes(iv)
            val parameterSpec = GCMParameterSpec(GCM_TAG_LENGTH * 8, iv)
            
            cipher.init(Cipher.ENCRYPT_MODE, key, parameterSpec)
            val encryptedData = cipher.doFinal(plainText.toByteArray())
            
            // 将IV和密文合并
            val encryptedWithIv = ByteArray(iv.size + encryptedData.size)
            System.arraycopy(iv, 0, encryptedWithIv, 0, iv.size)
            System.arraycopy(encryptedData, 0, encryptedWithIv, iv.size, encryptedData.size)
            
            return Base64.encodeToString(encryptedWithIv, Base64.DEFAULT)
        } catch (e: Exception) {
            // 出错时返回混淆的原文
            return obfuscateString(plainText)
        }
    }
    
    /**
     * 解密字符串
     * @param encryptedText Base64编码的密文
     * @return 明文
     */
    fun decrypt(encryptedText: String): String {
        try {
            val key = generateKey()
            val cipher = Cipher.getInstance(TRANSFORMATION)
            
            val encryptedWithIv = Base64.decode(encryptedText, Base64.DEFAULT)
            
            // 分离IV和密文
            val iv = ByteArray(GCM_IV_LENGTH)
            val encryptedData = ByteArray(encryptedWithIv.size - GCM_IV_LENGTH)
            System.arraycopy(encryptedWithIv, 0, iv, 0, iv.size)
            System.arraycopy(encryptedWithIv, iv.size, encryptedData, 0, encryptedData.size)
            
            val parameterSpec = GCMParameterSpec(GCM_TAG_LENGTH * 8, iv)
            cipher.init(Cipher.DECRYPT_MODE, key, parameterSpec)
            
            val decryptedData = cipher.doFinal(encryptedData)
            return String(decryptedData)
        } catch (e: Exception) {
            // 出错时返回反混淆的原文
            return deobfuscateString(encryptedText)
        }
    }
    
    /**
     * 简单字符串混淆
     */
    private fun obfuscateString(input: String): String {
        val chars = input.toCharArray()
        for (i in chars.indices) {
            chars[i] = (chars[i].code xor (i + 1)).toChar()
        }
        return Base64.encodeToString(String(chars).toByteArray(), Base64.DEFAULT)
    }
    
    /**
     * 简单字符串反混淆
     */
    private fun deobfuscateString(input: String): String {
        return try {
            val decoded = String(Base64.decode(input, Base64.DEFAULT))
            val chars = decoded.toCharArray()
            for (i in chars.indices) {
                chars[i] = (chars[i].code xor (i + 1)).toChar()
            }
            String(chars)
        } catch (e: Exception) {
            input
        }
    }
    
    /**
     * 预定义的加密字符串常量
     * 这些字符串在构建时会被加密
     */
    object EncryptedStrings {
        // 服务器相关字符串
        const val DEFAULT_SERVER_URL = "aGVsbG8gd29ybGQ="  // 占位符，实际值会在构建时替换
        
        /**
         * 获取解密后的服务器URL
         */
        fun getServerUrl(): String = decrypt(DEFAULT_SERVER_URL)
    }
    
} 