1

I'm getting this error while decrypting an AES128CBC encrypted JSON:

assertion failed: Block size and Initialization Vector must be the same length!: file ##### for iOS/CryptoSwift/Sources/CryptoSwift/AES.swift, line 97

I'm using the CryptoSwift Framework with the latest Xcode.

My Method:

func aes128(key: String, iv: String) throws -> String?{
        if let aes: AES = try AES(key: key, iv: iv, blockMode: .CBC){
            if let encrypted: [UInt8] = try aes.encrypt([UInt8](self.utf8), padding: PKCS7()){
                return String(data: NSData.withBytes(encrypted), encoding: NSUTF8StringEncoding)
            }
        }

        return nil
}

Call:

do{
    print(try dataStr.aes128("8e0c0e73f97f2eb386ad75ba86051334", iv: "aa17ffc4ea4b1eac8fa0b56872f34e5f"))   
}catch{

}
jww
  • 97,681
  • 90
  • 411
  • 885
Daniel R.
  • 31
  • 2
  • 5
  • Shouldn't the `iv` be `[UInt8]`? You're passing a `String`. – Tobi Nary Feb 25 '16 at 16:23
  • Also, key and iv look like hashes. You do realize that that is a bad idea, as it minimizes the key plane to hexadecimal strings? This makes brute force _so_ much easier. – Tobi Nary Feb 25 '16 at 16:26
  • Your key and iv are the same length, 32 bytes. Assuming you are using a 128 bit block size your iv should be 16 bytes. Take a look at this answer for ideas on how to use CryptoSwift: http://stackoverflow.com/a/30820691/887210 –  Feb 25 '16 at 16:48
  • Kenneth Bruno and @Jan Greve: Thanks, thanks, thanks!!! Now it's working. I'll post my new code as answer. – Daniel R. Feb 25 '16 at 19:25
  • @zaph I'm just going with what was asked in the question. If Common Crypto is a better way to go then tell the author of the question. –  Feb 25 '16 at 22:41
  • you can lookup my answer in this post https://stackoverflow.com/questions/46469164/how-to-do-aes-128-encryption-of-a-string-on-swift-xcode-and-send-it-as-post-to-t/46479667#46479667 – Au Ris Sep 29 '17 at 13:58

1 Answers1

0

My Method:

func aes128(key: [UInt8], iv: [UInt8]) throws -> String?{
    let data = NSData(base64EncodedString: self, options: NSDataBase64DecodingOptions(rawValue: 0))
    let dec = try AES(key: key, iv: iv, blockMode:.CBC).decrypt(data!.arrayOfBytes(), padding: PKCS7())
    let decData = NSData(bytes: dec, length: Int(dec.count))
    let result = NSString(data: decData, encoding: NSUTF8StringEncoding)
    return String(result!)
}

The call:

do{
    let secret: [UInt8] = self.getAuthSecret(.LoginSecret)!.byte
    let ivSlice = secret[0..<16]
    let ivArray = Array<UInt8>(ivSlice)

    let keySlice = secret[16..<32]
    let keyArray = Array<UInt8>(keySlice)

    print(try dataStr.aes128(keyArray, iv: ivArray))
}catch{

}
Daniel R.
  • 31
  • 2
  • 5
  • CryptoSwift, AES encryption is 500 to 1000 times slower than using Common Crypto, that may not be a concern for your use. CryptoSwift has not been well vetted and Common Crypto is FIPS 140-2 certified. – zaph Feb 29 '16 at 20:56