swift4 - 使用 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())
}
解决方案
错误 -4310 是 kCCKeySizeError(请参阅 CommonCryptoError.h)。这意味着您的密钥大小不合适。
看看这段代码,这尤其令人怀疑:
getSecretkey()?.data(using: .utf8)
如果密钥可解码为 UTF-8,则它不是正确的密钥。您的 IV 似乎也有同样的问题。我怀疑这generateRandomBytes()
并没有做到它所说的那样。由于您丢弃了随机 IV(解密器将需要),因此也无法解密此数据。您在输出中为它创建空间(这很好),但您从不编写它。
推荐阅读
- sql - 更新总和组
- python - 通过发布请求django将图像发送到服务器
- yocto - Yocto部署文件夹中的符号链接有什么用
- wordpress - 使用多个 wp 主机时,AWS 上的 Wordpress 站点无法正确连接到数据库
- vue.js - 为什么我们需要 vuex 而不仅仅是简单的全局对象
- r - R编程中的特征函数
- python-3.x - 如何在文本文件中的特定位置附加字符串
- android - 我的 android studio 没有从 3.5 更新到 3.6 版本
- python - 操作一个大文件python
- swiftui - @State var 不起作用,但非 State 变量起作用