iOS 字符串加密

作者: 云抱住阳光太阳没放弃发亮 | 来源:发表于2016-05-31 14:40 被阅读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
    }
}

相关文章

网友评论

    本文标题:iOS 字符串加密

    本文链接:https://www.haomeiwen.com/subject/iywcdttx.html