iOS基础·OC语法篇iOS DeveloperiOS 开发

iOS 字符串加密

2016-05-31  本文已影响500人  云抱住阳光太阳没放弃发亮

在Swift中通过调用OC的CommonCrypto库可以很方便的实现String字符串加密。

创建了一个swift和OC桥接的文件,引入头文件

#import <CommonCrypto/CommonCrypto.h>

扩展String类

extension String {
    
    func Md5() -> String {
        let str = self.cStringUsingEncoding(NSUTF8StringEncoding)
        let strLen = CUnsignedInt(self.lengthOfBytesUsingEncoding(NSUTF8StringEncoding))
        let digestLen = Int(CC_MD5_DIGEST_LENGTH)
        let result = UnsafeMutablePointer<CUnsignedChar>.alloc(digestLen)
        
        CC_MD5(str!, strLen, result)
        
        let hash = NSMutableString()
        for i in 0..<digestLen {
            hash.appendFormat("%02x", result[i])
        }
        
        result.dealloc(digestLen)
        
        return String(hash)
    }
    
    func Sha1() -> String {
        let data = self.dataUsingEncoding(NSUTF8StringEncoding)!
        var digest = [UInt8](count:Int(CC_SHA1_DIGEST_LENGTH), repeatedValue: 0)
        CC_SHA1(data.bytes, CC_LONG(data.length), &digest)
        let output = NSMutableString(capacity: Int(CC_SHA1_DIGEST_LENGTH))
        for byte in digest {
            output.appendFormat("%02x", byte)
        }
        return output as String
    }
}
上一篇下一篇

猜你喜欢

热点阅读