1、简介
在与后端服务器交互的过程中我们经常会用到MD5等加密方式,之前在OC中我们常用的方式是给NSString新增一个category,在category的.m文件中引入#import <CommonCrypto/CommonDigest.h>就可以使用其中的C加密函数CC_MD5了。那么在swift里由于CommonDigest.h 为OC中的类库所以我们要做的第一步便是搭桥。 最简单的方法就是创建一个OC的类然后根据提示创建相应的bridge文件,最后再删除OC文件,在bridge的头文件中到如CommonDigest,然后我们便可以在Swift里使用CC_MD5了。
2、Swift 中的 category
在swift中要实现OC中的category我们需要借助extension classname
3、创建String的Extension来实现标题中的3中加密或编码方式
//
// String+Security.swift
//
//
// Created by VcaiTech on 2017/5/15.
// Copyright © 2017年 Tang guifu. All rights reserved.
//
import Foundation
extension String {
func md5() -> String {
let str = self.cString(using: String.Encoding.utf8)
let strLen = CUnsignedInt(self.lengthOfBytes(using: String.Encoding.utf8))
let digestLen = Int(CC_MD5_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
CC_MD5(str!, strLen, result)
let hash = NSMutableString()
for i in 0 ..< digestLen {
hash.appendFormat("%02x", result[i])
}
result.deinitialize()
return String(format: hash as String)
}
func sha1() -> String {
let str = self.cString(using: String.Encoding.utf8)
let strLen = CUnsignedInt(self.lengthOfBytes(using: String.Encoding.utf8))
let digestLen = Int(CC_SHA1_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
CC_SHA1(str!, strLen, result)
let hash = NSMutableString()
for i in 0 ..< digestLen {
hash.appendFormat("%02x", result[i])
}
result.deinitialize()
return String(format: hash as String)
}
func base64decode() -> String? {
let decodeData:Data? = Data.init(base64Encoded: self, options: Data.Base64DecodingOptions.init(rawValue: 0))
guard let utf8Data = decodeData else{
return nil
}
let decodedStr:String? = String.init(data: utf8Data, encoding: String.Encoding.utf8)
return decodedStr
}
func base64encode() -> String? {
let utf8str:Data? = self.data(using: String.Encoding.utf8)
guard let utf8Data = utf8str else{
return nil
}
let base64Encoded:String = utf8Data.base64EncodedString(options: Data.Base64EncodingOptions.init(rawValue: 0))
return base64Encoded
}
}