两个知识点,一个是桥接一个是扩展
新建一个. h 头文件 我取名为 Header.h
#ifndef Header_h
#define Header_h
#import <CommonCrypto/CommonHMAC.h>
#import <CommonCrypto/CommonDigest.h>//md5
#endif /* Header_h */
路径为 项目名/所在文件价/头文件
项目名/http_bdy/other/Header.h
image.png对字符串扩展方便加密
import Foundation
enum CryptoAlgorithm {
case MD5, SHA1, SHA224, SHA256, SHA384, SHA512
var HMACAlgorithm: CCHmacAlgorithm {
var result: Int = 0
switch self {
case .MD5: result = kCCHmacAlgMD5
case .SHA1: result = kCCHmacAlgSHA1
case .SHA224: result = kCCHmacAlgSHA224
case .SHA256: result = kCCHmacAlgSHA256
case .SHA384: result = kCCHmacAlgSHA384
case .SHA512: result = kCCHmacAlgSHA512
}
return CCHmacAlgorithm(result)
}
var digestLength: Int {
var result: Int32 = 0
switch self {
case .MD5: result = CC_MD5_DIGEST_LENGTH
case .SHA1: result = CC_SHA1_DIGEST_LENGTH
case .SHA224: result = CC_SHA224_DIGEST_LENGTH
case .SHA256: result = CC_SHA256_DIGEST_LENGTH
case .SHA384: result = CC_SHA384_DIGEST_LENGTH
case .SHA512: result = CC_SHA512_DIGEST_LENGTH
}
return Int(result)
}
}
extension String {
func hmac(algorithm: CryptoAlgorithm) -> String {
let key = "DaMai"
let str = self.cString(using: String.Encoding.utf8)
let strLen = Int(self.lengthOfBytes(using: String.Encoding.utf8))
let digestLen = algorithm.digestLength
let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
let keyStr = key.cString(using: String.Encoding.utf8)
let keyLen = Int(key.lengthOfBytes(using: String.Encoding.utf8))
CCHmac(algorithm.HMACAlgorithm, keyStr!, keyLen, str!, strLen, result)
let digest = stringFromResult(result: result, length: digestLen)
result.deallocate(capacity: digestLen)
return digest
}
private func stringFromResult(result: UnsafeMutablePointer<CUnsignedChar>,
length: Int) -> String {
let hash = NSMutableString()
for i in 0..<length {
hash.appendFormat("%02x", result[i])
}
return String(hash)
}
}
class SignUtil{
var waitSignStr = String()
init(datas: inout [String:String]){
let keys = datas.sorted(by: {$0.0 < $1.0})
// let values = datas.sorted(by: {$0.1 < $1.1})//对value排序
for(mkey , mvalue) in keys {
if waitSignStr.isEmpty {
if !mvalue.isEmpty {
waitSignStr = mkey + "=" + mvalue
}else{
datas.removeValue(forKey: mkey)
}
} else {
if !mvalue.isEmpty {
waitSignStr = waitSignStr + "&" + mkey + "=" + mvalue
}else{
datas.removeValue(forKey: mkey)
}
}
}
waitSignStr = waitSignStr + "&key=uUwUCQTvZ70$a37Pf!CJhodg0u0$!Uw9"
print("加密串:\(waitSignStr)")
}
}
extension SignUtil {
func signInfo() -> String{
let hmacStr = waitSignStr.hmac(algorithm:.SHA1)
return hmacStr
}
}
使用,我这边是网络请求的时候加密参数用的,所以传的是字典,使用时根据实际情况而定
let signStr = SignUtil.init(datas: ¶ms).signInfo()
网友评论