我正在做3Des加密和解密。当我调用密码类的加密方法时,我得到CCCryptorStatus“ -4310”
请检查代码,让我知道我在代码中做错了什么
let mdKey = "12345678901234567890123456789012"
let md = MessageDigest(.md5)
let keydata = mdKey.data(using: String.Encoding.ascii)
md.bytes = keydata!.bytes
md.data = NSMutableData.init(data: keydata ?? Data())
let result = md.final()
print(result)
let objCipher = Cipher(algorithm: Cipher.Algorithm.tripleDES, options: [.ECBMode,.PKCS7Padding])
do{
let encription = try objCipher.encrypt(messageData!.bytes, key: keydata!.bytes)
print(encription)
}catch let errorMessage{
print(errorMessage)
}
//密码类方法//
public func encrypt(_ data: Data, key: Key) throws -> [UInt8] {
return try cryptoOperation(data, key: key, operation: .encrypt)
}
public func decrypt(_ data: Data, key: Key) throws -> [UInt8] {
return try cryptoOperation(data, key: key, operation: .decrypt)
}
fileprivate func cryptoOperation(_ data: Data, key: Key, operation: Operation) throws -> [UInt8] {
var dataOutMoved = 0
var outData = [UInt8](repeating: UInt8(0), count: Int(data.count + self.algorithm.blockSize))
let ivData = "iv-salt-string--".data(using: String.Encoding.ascii)//self.iv == nil ? nil : UnsafeRawPointer(self.iv!)
let status = CCCrypt(operation.rawValue, // operation
self.algorithm.rawValue, // algorithm
self.options.rawValue, // options
key, // key
key.count, // keylength
ivData!.bytes, // iv
data, // input data
data.count, // input length
&outData, // output buffer
outData.count, // output buffer length
&dataOutMoved) // output bytes real length
if status == CCCryptorStatus(kCCSuccess) {
return Array(outData[0..<dataOutMoved])
} else {
throw SCryptoError(rawValue: status)!
}
}
最佳答案
-4310是kCCKeySizeError
。看起来您正在传递MD5输出作为密钥。 MD5产生128位哈希。 3DES需要168位,112位或56位密钥。因此存在不匹配。我希望您正在使用3DES的事实表明您正在维护与某些非常旧的系统的兼容性(如果不兼容,请停止使用3DES)。您将需要探索旧系统如何管理其密钥。您不符合该系统另一端的要求。