CryptoSwift AES128-CBC与Swift

时间:2016-02-25 16:10:14

标签: ios swift encryption cryptography cryptoswift

我在解密AES128CBC加密的JSON时收到此错误:

  

断言失败:块大小和初始化向量必须是   相同的长度!:文件##### for   iOS / CryptoSwift / Sources / CryptoSwift / AES.swift,第97行

我正在使用CryptoSwift框架和最新的Xcode。

我的方法:

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
}

呼叫:

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

}

1 个答案:

答案 0 :(得分:0)

我的方法:

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

电话:

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{

}