我一直在尝试使用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())
}
错误-4310是kCCKeySizeError(请参阅CommonCryptoError.h)。这意味着你的钥匙尺寸不合适。
看看这段代码,特别是非常可疑:
getSecretkey()?.data(using: .utf8)
如果一个密钥可以解码为UTF-8,那么它不是一个合适的密钥。你的IV似乎有同样的问题。我怀疑generateRandomBytes()
并没有像它所说的那样做。它也无法解密这些数据,因为你扔掉了随机IV(解密器需要它)。你在输出中为它创造了空间(这很好),但你永远不会写它。