• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

swiftaes加密

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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中不可以对变量使用取地址操作 

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap