Ghafar Tanveer
Ghafar Tanveer

Reputation: 1

getting CCCryptorStatus "-4310"

i'm doing 3Des encryption and decryption. I'm getting CCCryptorStatus "-4310" when i call encrypt method of cipher class plz check the code and let me know if i'm doing something wrong in my code

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)
    }

// Cipher Class Methods//

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)!
    }
}

Upvotes: 0

Views: 996

Answers (1)

Rob Napier
Rob Napier

Reputation: 299683

-4310 is kCCKeySizeError. It looks like you're passing an MD5 output as the key. MD5 produces a 128-bit hash. 3DES requires a 168-, 112-, or 56-bit key. So there's a mismatch. The fact that you're using 3DES I hope indicates that you're maintaining compatibility with some very old system (if not, stop using 3DES). You'll need to explore how that old system manages its keys. You're not matching what the other side of this system requires.

Upvotes: 1

Related Questions