在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
1、需要引入 libSystem.dylib 2、添加NSData 类扩展,代码如下 extension NSData{ func AES128Crypt(operation:CCOperation,keyData:NSData)->NSData?{ let keyBytes = keyData.bytes let keyLength = Int(kCCKeySizeAES256) let dataLength = self.length let dataBytes = self.bytes let cryptLength = Int(dataLength+kCCBlockSizeAES128) var cryptPointer = UnsafeMutablePointer<UInt8>.alloc(cryptLength) let algoritm: CCAlgorithm = CCAlgorithm(kCCAlgorithmAES128) let option: CCOptions = CCOptions(kCCOptionECBMode + kCCOptionPKCS7Padding) var numBytesEncrypted = UnsafeMutablePointer<Int>.alloc(1) numBytesEncrypted.initialize(0) var cryptStatus = CCCrypt(operation, algoritm, option, keyBytes, keyLength, nil, dataBytes, dataLength, cryptPointer, cryptLength, numBytesEncrypted) if CCStatus(cryptStatus) == CCStatus(kCCSuccess) { let len = Int(numBytesEncrypted.memory) var data:NSData = NSData(bytesNoCopy: cryptPointer, length: len) numBytesEncrypted.dealloc(1) return data } else { numBytesEncrypted.dealloc(1) cryptPointer.dealloc(cryptLength) return nil } } static func test(){ let keyString = "12345678901234567890123456789012" let keyData: NSData! = (keyString as NSString).dataUsingEncoding(NSUTF8StringEncoding) as NSData! let message = "Don´t try to read this text. Top Secret Stuff" let data: NSData! = (message as NSString).dataUsingEncoding(NSUTF8StringEncoding) as NSData! let result:NSData? = data.AES128Crypt(CCOperation(kCCEncrypt), keyData: keyData) println("encrypt = \(result)") let oldData = result?.AES128Crypt(CCOperation(kCCDecrypt), keyData: keyData) println("decrypt = \(oldData)") } } 3、swift中指针的使用
c/c++中指针对应swift中的UnsafePointer & UnsafeMutablePointer
UnsafePointer 类型指向的内容不可变;UnsafeMutablePointer 类型指向的内容可以修改
swift中不可以对变量使用取地址操作
|
请发表评论