//
//  AESCrypto.swift
//  PhoneManager
//
//  Created by edy on 2025/5/21.
//

import Foundation
import CommonCrypto
import CryptoKit

struct AESCrypto {
    // 需要修改为与安卓一致的密钥
    private static let key = "z1lle6aeg531um0k"
    
    static func encryptGCM(_ string: String) -> String? {
        guard let data = string.data(using: .utf8),
              let keyData = key.data(using: .utf8) else { return nil }
        
        do {
            // CryptoKit 自动生成 nonce，长度可能与安卓不一致
            let nonce = AES.GCM.Nonce()
            let symmetricKey = SymmetricKey(data: keyData)
            let sealedBox = try AES.GCM.seal(data, using: symmetricKey, nonce: nonce)
            let combined = sealedBox.combined
            return combined?.base64EncodedString()
        } catch {
            print("加密错误: \(error)")
            return nil
        }
    }
    
    /// AES-GCM 解密方法
    /// - Parameter encrypted: 加密后的 base64 字符串（包含 nonce 和认证标签）
    /// - Returns: 返回解密后的原始字符串
    static func decryptGCM(_ encrypted: String) -> String? {
        guard let combinedData = Data(base64Encoded: encrypted),
              let keyData = key.data(using: .utf8) else { return nil }
        
        do {
            // 创建 SymmetricKey
            let symmetricKey = SymmetricKey(data: keyData)
            
            // 从组合数据创建 sealed box
            let sealedBox = try AES.GCM.SealedBox(combined: combinedData)
            
            // 解密数据
            let decryptedData = try AES.GCM.open(sealedBox, using: symmetricKey)
            
            // 转换为字符串
            return String(data: decryptedData, encoding: .utf8)
            
        } catch {
            print("解密错误: \(error)")
            return nil
        }
    }
}
