iOS猛码计划

Swift 获取七牛云上传 token

2018-06-30  本文已影响16人  Caiflower

记得在桥接文件中引用相关类

/* 七牛云**/
#import "Qiniu/QiniuSDK.h"
#import "HappyDNS/HappyDNS.h"
/// 加密相关
#import <CommonCrypto/CommonHMAC.h>

具体流程如下

final class QiniuAuthPolicy {
    /// 七牛上的文件路径
    let scope: String
    /// token 过期时间,
    let expires: Int

    static let `default` = QiniuAuthPolicy()
    ///
    ///
    /// - Parameters:
    ///   - scope: 文件路径
    ///   - expires: token过期时间, 默认 3600
    init(_ scope: String = "heicarbook", expires: Int = 3600) {
        self.scope = scope
        self.expires = expires
    }
    
    /// 根据accessKey,secretKey 获取 token
    ///
    /// - Parameters:
    ///   - accessKey: accessKey
    ///   - secretKey: secretKey
    /// - Returns: token
    func makeToken(accessKey: String, secretKey: String) -> String {
        
        let secretKeyStr = secretKey.cString(using: .utf8)
        
        let policy = paramsToJson()
        
        guard let policyData = policy.data(using: .utf8) else {
            return ""
        }
        guard let encodedPolicy = QN_GTM_Base64.string(byWebSafeEncoding: policyData, padded: true) else {
            return ""
        }
        
        guard let encodedPolicyStr = encodedPolicy.cString(using: .utf8) else {
            return ""
        }
        let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: Int(CC_SHA1_DIGEST_LENGTH))
        CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA1), secretKeyStr, strlen(secretKeyStr), encodedPolicyStr, strlen(encodedPolicyStr), result)
        let resultData = Data(bytes: result, count: Int(CC_SHA1_DIGEST_LENGTH))
        let encodedDigest = QN_GTM_Base64.string(byWebSafeEncoding: resultData, padded: true) ?? ""
        
        let token = "\(accessKey):\(encodedDigest):\(encodedPolicy)"
        myLog("七牛 toekn ==> \(token)")
        return token
    }
    /// 参数转 json
    private func paramsToJson() -> String {
        var deadline: time_t = 0
        time(&deadline)
        deadline += expires > 0 ? expires : 3600
        let dict: [String: Any] = ["scope": scope, "deadline": deadline]
        if !JSONSerialization.isValidJSONObject(dict) {
            return ""
        } else {
            guard let data = try? JSONSerialization.data(withJSONObject: dict, options: []) else {
                return ""
            }
            let json = String(data: data, encoding: .utf8)
            return json ?? ""
        }
    }
}

然后就可以愉快的获取 token 了

static let  qiniuAccessKey = "你的七牛AccessKey"
static let  qiniuSecertkey = "你的七牛Secertkey"
let toekn = QiniuAuthPolicy.default.makeToken(accessKey: qiniuAccessKey, secretKey: qiniuSecertkey)
上一篇 下一篇

猜你喜欢

热点阅读