/**
 * 使用随机IV加密数据
 * @param plainData 明文数据
 * @return 加密后的数据，前16字节为IV
 */
- (NSData *)encryptWithRandomIV:(NSData *)plainData {
    if (plainData.length == 0) {
        return [NSData data];
    }
    
    // 1. 生成16字节随机IV
    uint8_t iv[16];
    int status = SecRandomCopyBytes(kSecRandomDefault, sizeof(iv), iv);
    if (status != errSecSuccess) {
        return nil; // 随机失败
    }
    
    // 2. 创建IV数据
    NSData *ivData = [NSData dataWithBytes:iv length:16];
    
    // 3. 加密数据
    NSMutableData *encryptedData = [NSMutableData dataWithCapacity:plainData.length];
    const uint8_t *plainBytes = plainData.bytes;
    
    for (NSUInteger i = 0; i < plainData.length; i++) {
        uint8_t cipherByte = plainBytes[i] ^ iv[i % 16];
        [encryptedData appendBytes:&cipherByte length:1];
    }
    
    // 4. 返回IV + 加密数据
    NSMutableData *resultData = [NSMutableData dataWithData:ivData];
    [resultData appendData:encryptedData];
    
    return resultData;
}

/**
 * 解密数据
 * @param encryptedData 加密后的数据，前16字节为IV
 * @return 解密后的明文数据
 */
- (NSData *)decryptWithRandomIV:(NSData *)encryptedData {
    if (encryptedData.length < 16) {
        return [NSData data];
    }
    
    // 1. 提取IV（前16字节）
    NSData *ivData = [encryptedData subdataWithRange:NSMakeRange(0, 16)];
    const uint8_t *iv = ivData.bytes;
    
    // 2. 提取密文数据（从第17字节开始）
    NSData *cipherData = [encryptedData subdataWithRange:NSMakeRange(16, encryptedData.length - 16)];
    const uint8_t *cipherBytes = cipherData.bytes;
    
    // 3. 解密数据
    NSMutableData *plainData = [NSMutableData dataWithCapacity:cipherData.length];
    
    for (NSUInteger i = 0; i < cipherData.length; i++) {
        uint8_t plainByte = cipherBytes[i] ^ iv[i % 16];
        [plainData appendBytes:&plainByte length:1];
    }
    
    return plainData;
}

/**
 * 将NSData转换为十六进制字符串
 */
- (NSString *)dataToHexString:(NSData *)data {
    if (!data || data.length == 0) {
        return @"";
    }
    
    NSMutableString *hexString = [NSMutableString stringWithCapacity:data.length * 2];
    const unsigned char *bytes = data.bytes;
    
    for (NSUInteger i = 0; i < data.length; i++) {
        [hexString appendFormat:@"%02X", bytes[i]];
    }
    
    return hexString;
}

/**
 * 将十六进制字符串转换为NSData
 */
- (NSData *)hexStringToData:(NSString *)hexString {
    if (!hexString || hexString.length == 0) {
        return [NSData data];
    }
    
    NSMutableData *data = [NSMutableData dataWithCapacity:hexString.length / 2];
    unsigned char byte;
    char byteChars[3] = {'\0','\0','\0'};
    
    for (NSUInteger i = 0; i < hexString.length; i += 2) {
        byteChars[0] = [hexString characterAtIndex:i];
        byteChars[1] = [hexString characterAtIndex:i+1];
        byte = strtol(byteChars, NULL, 16);
        [data appendBytes:&byte length:1];
    }
    
    return data;
}