swiftcryptographyswift4commoncrypto

cccrypt is generating strange output in swift 4


I trying to write an encryption (AESCBC256) function based on CCCrypt and the CCCrypt is generating a random value.

for example, when I pass 1234567 to function it'll return "HlFP2rCmycZS1269Cm47Q==" or "TTuSJrBcsOmOCDHc5IQ8Dw==" for the same iv and Key.

here's the iv: b5f89591 and the key is : 366e9c1b4b2ed2b1daf751d7500aaa01

func encrypt(Value: String)->String{
    let keyData = keyString.data(using: .utf8, allowLossyConversion: false)!
    let iv = SecretKey.data(using: .utf8, allowLossyConversion: false)!
    let message       = SecretKey+Value
    let data = message.data(using: .utf8, allowLossyConversion: false)!
    let cryptData    = NSMutableData(length: Int(data.count) + kCCBlockSizeAES128)!
    let keyLength              = size_t(kCCKeySizeAES256)
    let operation: CCOperation = CCOperation(UInt32(kCCEncrypt))
    let algoritm:  CCAlgorithm = CCAlgorithm(UInt32(kCCAlgorithmAES128))
    let options:   CCOptions   = CCOptions(UInt32(kCCOptionPKCS7Padding))
    var numBytesEncrypted :size_t = 0
    let cryptStatus = CCCrypt(operation,
                              algoritm,
                              options,
                              keyData.withUnsafeBytes { (bytes: UnsafePointer<UInt8>) -> UnsafePointer<UInt8> in return bytes},
                              keyLength,
                              iv.withUnsafeBytes { (bytes: UnsafePointer<UInt8>) -> UnsafePointer<UInt8> in return bytes},
                              data.withUnsafeBytes { (bytes: UnsafePointer<UInt8>) -> UnsafePointer<UInt8> in return bytes},
                              data.count,
                              cryptData.mutableBytes, cryptData.length,
                              &numBytesEncrypted)

    if UInt32(cryptStatus) == UInt32(kCCSuccess) {
        cryptData.length = Int(numBytesEncrypted)
        return String(describing: cryptData.base64EncodedString(options: .lineLength64Characters))
    }else{
        return ""
    }
}

Solution

  • Your IV is the wrong length. It's 8 bytes long, but AES requires a 16 byte IV, so it's reading random data out of memory for the other 8 bytes.