Generating HMAC-SHA256 from Byte-Array in Swift

3.4k views Asked by At

I want to create a signature for the myJD REST-API. But the first snippet is not working. I talked to the support and they told me that I need the unhexed key to create the correct hash. So I created a Byte-Array of the Hex-Value and changed the code to work again (see second snippet). Both methods have the same result. Link to API documentation: https://docs.google.com/document/d/1IGeAwg8bQyaCTeTl_WyjLyBPh4NBOayO0_MAmvP5Mu4/edit?pref=2&pli=1

First:

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)
    }
}

Second:

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

There are 0 answers