首页 > 解决方案 > 使用 CommonCrypto 加密在 Swift4.2 中不起作用。抛出错误 4301

问题描述

我一直在尝试在 swift 4.2 中使用 CommonCrypto 库来实现加密。但是没有运气,最终出现了一些未知的错误。

有人请看这段代码并帮助我。

func encrypty(data value: String) -> EncryptionResult {

    guard var messageData = value.data(using: .utf8), var key = getSecretkey()?.data(using: .utf8)  else {
        return EncryptionResult.failure
    }
    //iv ata
    guard let ivData = generateRandomBytes(of: Int32(SecurityConstants.blockSize))?.data(using: .utf8) else {
        return EncryptionResult.failure
    }
    //output
    var outputData = Data(count: (messageData.count + SecurityConstants.blockSize + ivData.count))
    var localOutput = outputData
    //output length
    var outputLength: size_t = 0

    //encyrption
    let status = key.withUnsafeBytes { keyBytes in
        messageData.withUnsafeBytes { messageBytes in
            localOutput.withUnsafeMutableBytes { mutableOutput in
                ivData.withUnsafeBytes { ivDataBytes in
                    CCCrypt( CCOperation(kCCEncrypt),
                             CCAlgorithm(kCCAlgorithmAES128),
                             CCOptions(kCCOptionPKCS7Padding),
                             keyBytes,
                             key.count,
                             ivDataBytes,
                             messageBytes,
                             messageData.count,
                             mutableOutput,
                             outputData.count,
                             &outputLength)
                }
            }
        }
    }
    guard status == Int32(kCCSuccess) else {
        logError("Error in encryption")
        return EncryptionResult.failure
    }
    outputData.count = outputLength
    return EncryptionResult.success(value: outputData.base64EncodedString())
}

标签: swift4encryption-symmetriccommoncrypto

解决方案


错误 -4310 是 kCCKeySizeError(请参阅 CommonCryptoError.h)。这意味着您的密钥大小不合适。

看看这段代码,这尤其令人怀疑:

getSecretkey()?.data(using: .utf8)

如果密钥可解码为 UTF-8,则它不是正确的密钥。您的 IV 似乎也有同样的问题。我怀疑这generateRandomBytes()并没有做到它所说的那样。由于您丢弃了随机 IV(解密器将需要),因此也无法解密此数据。您在输出中为它创建空间(这很好),但您从不编写它。


推荐阅读