在Swift中从Byte-Array生成HMAC-SHA256

时间:2016-02-25 07:30:12

标签: xcode swift jdownloader

我想为myJD REST-API创建签名。但第一个片段不起作用。我谈到了支持,他们告诉我,我需要 unhexed 键来创建正确的哈希。所以我创建了一个十六进制值的字节数组,并将代码更改为再次工作(请参阅第二个代码段)。两种方法都有相同的结果。 链接到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
}

0 个答案:

没有答案