阅读 239

Swift MD5和SHA256加密

代码如下
  • 倒入加密库
import CommonCrypto
复制代码
  • 在字符串的扩展里实现加密得到加密数组并转换为base64的字符串
extension String {
    
    func MD5Encrypy() -> String {
        guard self.count > 0 else {
            fatalError("md5加密无效的字符串")
        }
        let cCharArray = self.cString(using: .utf8)
        var uint8Array = [UInt8](repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH))
        CC_MD5(cCharArray, CC_LONG(cCharArray!.count - 1), &uint8Array)
        let data = Data(bytes: &uint8Array, count: Int(CC_MD5_DIGEST_LENGTH))
        let base64String = data.base64EncodedString()
        return base64String
    }
    
    func HMAC_Sign(algorithm: CCHmacAlgorithm, keyString: String, dataString: String) -> String {
        if algorithm != kCCHmacAlgSHA1 && algorithm != kCCHmacAlgSHA256 {
            print("Unsupport algorithm.")
            return ""
        }
        let keyData = keyString.data(using: .utf8)! as NSData
        let strData = dataString.data(using: .utf8)! as NSData
        let len = algorithm == CCHmacAlgorithm(kCCHmacAlgSHA1) ? CC_SHA1_DIGEST_LENGTH : CC_SHA256_DIGEST_LENGTH
        var cHMAC = [UInt8](repeating: 0, count: Int(len))
        CCHmac(algorithm, keyData.bytes, keyData.count, strData.bytes, strData.count, &cHMAC)
        let data = Data(bytes: &cHMAC, count: Int(len))
        let base64String = data.base64EncodedString()
        return base64String
    }
    
}
复制代码
文章分类
iOS
文章标签