1

我想为 myJD REST-API 创建一个签名。但是第一个片段不起作用。我与支持人员交谈,他们告诉我我需要未使用十六进制的密钥来创建正确的哈希。所以我创建了一个十六进制值的字节数组并更改了代码以再次工作(参见第二个片段)。两种方法具有相同的结果。API 文档链接:https ://docs.google.com/document/d/1IGeAwg8bQyaCTeTl_WyjLyBPh4NBOayO0_MAmvP5Mu4/edit?pref=2&pli=1

第一的:

import Foundation

extension String{    
    func hmacSHA256(key: String) -> String {
        let str = self.cStringUsingEncoding(NSUTF8StringEncoding)
        let strLen = Int(self.lengthOfBytesUsingEncoding(NSUTF8StringEncoding))
        let digestLen = Int(CC_SHA256_DIGEST_LENGTH)
        let result = UnsafeMutablePointer<CUnsignedChar>.alloc(digestLen)
        let keyStr = key.cStringUsingEncoding(NSUTF8StringEncoding)!
        let keyLen = Int(key.lengthOfBytesUsingEncoding(NSUTF8StringEncoding))

        CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA256), keyStr, keyLen, str!, strLen, result)

        let digest = stringFromResult(result, length: digestLen)

        result.dealloc(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)
    }
}

第二:

func hmacSHA256_2(key: String) -> String {
    //let cKey = key.dataUsingEncoding(NSUTF8StringEncoding)!
    let bKey = Array(key.utf8)
    let bData = Array(self.utf8)
    //let cData = self.dataUsingEncoding(NSUTF8StringEncoding)!

    var cHMAC = [CUnsignedChar](count: Int(CC_SHA256_DIGEST_LENGTH), repeatedValue: 0)
    CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA256), bKey, Int(bKey.count), bData, Int(bData.count), &cHMAC)

    let output = NSMutableString(capacity: Int(CC_SHA256_DIGEST_LENGTH))

    for byte in cHMAC {
        output.appendFormat("%02hhx", byte)
    }

    return output as String
}
4

0 回答 0