You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift基于CommonCrypto实现AES256时加密正常解密不匹配问题排查

代码问题分析与修复方案

问题根因

你遇到的本地解密失败问题核心来自两个常见错误:

  1. 指针类型未正确绑定:代码中调用CCCrypt时,从Data的withUnsafeBytes方法拿到的是原始内存指针,没有绑定到UInt8类型就直接传入方法。这种未定义行为在部分场景下会凑巧运行正常(所以加密后的数据服务端可以正常解密),但本地解密时很容易因为指针解析错误导致数据异常,解密失败。
  2. 密文处理逻辑不匹配:如果你加密后会把IV拼在密文前再做传输/存储,服务端会自动拆分前16位为IV、剩余部分为密文解密,但你本地解密时没有做对应的拆分,直接把拼接后的完整数据传入解密方法,也会直接解密失败。

修复方案

首先修改crypt方法的指针获取逻辑,正确绑定UInt8类型:

private func crypt(input: Data, operation: CCOperation) throws -> Data {
    var outLength = Int(0)
    var outBytes = [UInt8](repeating: 0, count: input.count + kCCBlockSizeAES128)
    var status: CCCryptorStatus = CCCryptorStatus(kCCSuccess)
    
    input.withUnsafeBytes { inputBuffer in
        let inputBytes = inputBuffer.bindMemory(to: UInt8.self).baseAddress!
        iv.withUnsafeBytes { ivBuffer in
            let ivBytes = ivBuffer.bindMemory(to: UInt8.self).baseAddress!
            key.withUnsafeBytes { keyBuffer in
                let keyBytes = keyBuffer.bindMemory(to: UInt8.self).baseAddress!
                status = CCCrypt(operation,
                                 CCAlgorithm(kCCAlgorithmAES128),
                                 CCOptions(kCCOptionPKCS7Padding),
                                 keyBytes,
                                 key.count,
                                 ivBytes,
                                 inputBytes,
                                 input.count,
                                 &outBytes,
                                 outBytes.count,
                                 &outLength)
            }
        }
    }
    
    guard status == kCCSuccess else {
        throw Error.cryptoFailed(status: status)
    }
    return Data(outBytes[0..<outLength])
}

如果是密文拼接问题,解密前先拆分数据前16位作为IV,剩余部分作为密文传入解密方法即可。

内容的提问来源于stack exchange,提问作者Nah

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 18:06:02