CryptoSwift AES128-CBC with Swift

Daniel R. Source

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


    print(try dataStr.aes128("8e0c0e73f97f2eb386ad75ba86051334", iv: "aa17ffc4ea4b1eac8fa0b56872f34e5f"))   



answered 3 years ago Daniel R. #1

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:

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


comments powered by Disqus