Swift 实现腾讯云 TC3-HMAC-SHA256 签名方法

2020-03-25 14:39:11 浏览数 (1)

cloud.tencent.apicloud.tencent.api

最近在接入一些腾讯云的API,腾讯是不是歧视我 iOS 没有 OC 示例,也没有 Swift 示例,可能是面向服务器的吧,但是边上安卓的童鞋直接复制JAVA代码就跑起来~~~我难受。

最看不起别人拿来主义,最希望自己可以 Command C

更难受的是我用的是 Swift, 系统没有现成的加密库,但是真的不想又引入一个第三方库,这里指的是这个库 CryptoSwift,当然不Care的童鞋直接pod install就好,这个无非是个人喜好,100来行代码可以解决的问题自己试试不香吗~

准备

在桥接文件里导入 #import <CommonCrypto/CommonHMAC.h>

桥接文件在你的Swift工程里面创建一个OC文件,Xcode就会帮你创建好啦。

代码

代码不多,我直接贴这里了,要的直接拷贝就好,也欢迎直接去GitHub中ZYCrypto给予一个小小的Star:

代码语言:txt复制
import Foundation

extension String {
    func hmac(by algorithm: Algorithm, key: [UInt8]) -> [UInt8] {
        var result = [UInt8](repeating: 0, count: algorithm.digestLength())
        CCHmac(algorithm.algorithm(), key, key.count, self.bytes, self.bytes.count, &result)
        return result
    }
    
    func hashHex(by algorithm: Algorithm) -> String {
        return algorithm.hash(string: self).hexString
    }
    
     func hash(by algorithm: Algorithm) -> [UInt8] {
        return algorithm.hash(string: self)
     }
}


enum Algorithm {
    case MD5, SHA1, SHA224, SHA256, SHA384, SHA512
    
    func algorithm() -> 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)
    }
    
    func digestLength() -> Int {
        var result: CInt = 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)
    }
    
    func hash(string: String) -> [UInt8] {
        var hash = [UInt8](repeating: 0, count: self.digestLength())
        switch self {
        case .MD5:    CC_MD5(   string.bytes, CC_LONG(string.bytes.count), &hash)
        case .SHA1:   CC_SHA1(  string.bytes, CC_LONG(string.bytes.count), &hash)
        case .SHA224: CC_SHA224(string.bytes, CC_LONG(string.bytes.count), &hash)
        case .SHA256: CC_SHA256(string.bytes, CC_LONG(string.bytes.count), &hash)
        case .SHA384: CC_SHA384(string.bytes, CC_LONG(string.bytes.count), &hash)
        case .SHA512: CC_SHA512(string.bytes, CC_LONG(string.bytes.count), &hash)
        }
        return hash
    }
}

extension Array where Element == UInt8 {
    var hexString: String {
        return self.reduce(""){$0   String(format: "x", $1)}
    }
    
    var base64String: String {
        return self.data.base64EncodedString(options: Data.Base64EncodingOptions.lineLength76Characters)
    }
    
    var data: Data {
        return Data(self)
    }
}

extension String {
    var bytes: [UInt8] {
        return [UInt8](self.utf8)
    }
}

extension Data {
    var bytes: [UInt8] {
        return [UInt8](self)
    }
}

从 swift 加密 抄了一点, 直接使用无法实现需求,同时好像代码太OC了,所以改了改,但是还是要在此表示感谢。

使用的话非常简单

HMAC
代码语言:txt复制
let tData = "test string".hmac(by: .SHA256, key: "key string".bytes)
let oDada = "other test string".hamc(by: .SHA256, key: tData)
let signature = oData.hexSting.lowercased()
HASH
代码语言:txt复制
let sha256Hash = "test string".hashHex(by: .SHA256)
let md5Hash = "test string".hash(by: .MD5).base64String
腾讯云 TC3-HMAC-SHA256 签名

这是 https://cloud.tencent.com/document/product/1131/42337 腾讯云文档的一个接口鉴权文档,前面说了,很遗憾,没有Swift 示例,也可能是因为iOS没有现成的加密工具有关。

主要还是加密功能的实现,实现了对应的加密方法,一切都按照流程来就好。

腾讯云 TC3-HMAC-SHA256 签名示例:

代码语言:txt复制
let secretId  = "AKIDz8krbsJ5yKBZQpn74WFkmLPx3EXAMPLE"
let secretKey = "Gu5t9xGARNpq86cd98joQYCN3EXAMPLE"
let action = "DescribeInstances"
let service = "cvm"
let host = "cvm.tencentcloudapi.com"
let region = "ap-guangzhou"
let version = "2017-03-12"
let algorithm = "TC3-HMAC-SHA256"
let timestampInterval: TimeInterval = 1551113065
let timestamp = "(Int(timestampInterval))"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
//注意时区,否则容易出错
dateFormatter.timeZone = TimeZone(identifier: "UTC")
let date = dateFormatter.string(from: Date(timeIntervalSince1970: timestampInterval))

// ************* 步骤 1:拼接规范请求串 *************

let httpRequestMethod = "POST"
let canonicalUri = "/"
let canonicalQueryString = ""
let canonicalHeaders = "content-type:application/json; charset=utf-8n"   "host:"   host   "n"
let signedHeaders = "content-type;host"
let payload = "{"Limit": 1, "Filters": [{"Values": ["\u672a\u547d\u540d"], "Name":"instance-name"}]}"
let hashedRequestPayload = payload.hashHex(by: .SHA256)
let canonicalRequest = httpRequestMethod   "n"   canonicalUri   "n"   canonicalQueryString   "n"
      canonicalHeaders   "n"   signedHeaders   "n"   hashedRequestPayload;
print("第一步结果:", canonicalRequest)

// ************* 步骤 2:拼接待签名字符串 *************
let credentialScope = date   "/"   service   "/"   "tc3_request"
let hashedCanonicalRequest = canonicalRequest.hashHex(by: .SHA256)
let stringToSign = algorithm   "n"   timestamp   "n"   credentialScope   "n"  
hashedCanonicalRequest
print("第二步结果:", stringToSign)

// ************* 步骤 3:计算签名 *************
let secretDate = date.hmac(by: .SHA256, key: ("TC3"   secretKey).bytes)
let secretService = service.hmac(by: .SHA256, key: secretDate)
let secretSigning = "tc3_request".hmac(by: .SHA256, key: secretService)
let signature = stringToSign.hmac(by: .SHA256, key: secretSigning).hexString.lowercased()
print("第三步结果:", signature)

// ************* 步骤 4:拼接 Authorization *************
let authorization = "TC3-HMAC-SHA256 "   "Credential="   secretId   "/"   credentialScope   ", "
  "SignedHeaders="   signedHeaders   ", "   "Signature="   signature
print("第四步结果:", authorization)
textView.text  = "第四步结果:"   authorization   "n"
var headerParams = [String: Any]()
headerParams["Host"]           = host
headerParams["Authorization"]  = authorization
headerParams["Content-Type"]   = "application/json; charset=utf-8"
headerParams["X-TC-Action"]    = action
headerParams["X-TC-Timestamp"] = timestamp
headerParams["X-TC-Version"]   = version
//然后例如AFN,可以使用AFHTTPRequestSerializer 的 requestSerializer 写入到请求头
//  for headerParam in headerParams {
//      requestSerializer.setValue(headerParam.value, forHTTPHeaderField: headerParam.key)
//  }

这是加密结果,和文档中结果一致:

TC3-HMAC-SHA256TC3-HMAC-SHA256

0 人点赞