-1

I have been trying to implement encryption using CommonCrypto library in swift 4.2. But no luck, ending up with some unknown error.

Somebody please look at this code and help me.

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())
}
Vinay Hosamane
  • 346
  • 1
  • 5
  • 15

1 Answers1

0

Error -4310 is kCCKeySizeError (see CommonCryptoError.h). That means your key is not the right size.

Looking at this code, this in particular is very suspicious:

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

If a key is decodable as UTF-8, it's not a proper key. You seem to have the same problem with your IV. I suspect that generateRandomBytes() does not quite do what it says it does. It's also not going to be possible to decrypt this data because you throw away the random IV (which the decryptor will require). You create room for it in the output (which is good), but you never write it.

Rob Napier
  • 286,113
  • 34
  • 456
  • 610
  • Thank you Rob for the insights. I have just updated the question, the error is -4301, which says kCCBufferTooSmall. And also I don’t really need iv here , so I will make it nil. The encryption key is of size 32 bytes. This one I am deriving with the password. What I had done was, getRandomByes was returning me Data type, but I was converting that into String. Would that make difference if I convert string back into data with utf8 encoding. It will remain same right? – Vinay Hosamane Feb 09 '19 at 03:28
  • And also my key size is 32 bytes. And I am using AES 128 algorithm, would that affect my encryption? – Vinay Hosamane Feb 09 '19 at 04:18
  • "And also I don’t really need iv here , so I will make it nil." You need an IV if you ever encrypt two messages with this same key. Otherwise you break the security model of CBC and risk decryption of the message. – Rob Napier Feb 09 '19 at 15:29
  • If you convert random data to UTF8, you're going to get nil. It is very unlikely that a random sequence of bytes will happen to be valid UTF8. Your key should only ever be Data, never a String. – Rob Napier Feb 09 '19 at 15:30
  • The "AES 128" algorithm is unfortunately confusing naming. It means the block size is 128-bits, not that the key is 128 bits. In other contexts, the 128 refers to the key size, but not here. (This is doubly confusing, because AES *always* has a 128-bit block size; it's part of the definition.) – Rob Napier Feb 09 '19 at 15:32
  • What is `SecurityConstants.blockSize`? It should be 16. If it's too small, then that would lead to -4301. But to debug this, you should post working code. Get rid of your helper functions, and just write this in a playground in the most basic way. Then build up from there. – Rob Napier Feb 09 '19 at 15:35
  • Thank you Rob. Got it working, the problem was with String to data and reverse conversions. – Vinay Hosamane Feb 11 '19 at 09:30