使用CommonCrypto在Swift4.2中加密不起作用。投掷错误4301

问题描述 投票:-1回答:1

我一直在尝试使用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())
}
swift4 encryption-symmetric commoncrypto
1个回答
0
投票

错误-4310是kCCKeySizeError(请参阅CommonCryptoError.h)。这意味着你的钥匙尺寸不合适。

看看这段代码,特别是非常可疑:

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

如果一个密钥可以解码为UTF-8,那么它不是一个合适的密钥。你的IV似乎有同样的问题。我怀疑generateRandomBytes()并没有像它所说的那样做。它也无法解密这些数据,因为你扔掉了随机IV(解密器需要它)。你在输出中为它创造了空间(这很好),但你永远不会写它。

© www.soinside.com 2019 - 2024. All rights reserved.