HMAC SHA256 in C# vs HMAC SHA256 in Swift don't match

断了今生、忘了曾经 提交于 2020-06-29 06:42:21

问题


Using the 'standard' HMACSHA256 technique in dotnetcore C# I can produce a hashed string as follows:

private static void Test()
{
    var hmac = new HMACSHA256(Encoding.UTF8.GetBytes("testingkey"));
    var theHash = hmac.ComputeHash(Encoding.UTF8.GetBytes("testingstringtohash"));
    string signature = Convert.ToBase64String(theHash);
    Console.WriteLine(signature);
}
//Produces yg/9NCAm5IIwGKJK80PyUeBWkzEUwZswvC3OVnTnT80=

To do the same in swift (solution from this answer seems to be the 'standard' that people are using)

func HashTest() {
    let hash = "testingstringtohash".hmac(algorithm: .SHA256, key: "testingkey")
    //hash ca0ffd342026e4823018a24af343f251e056933114c19b30bc2dce5674e74fcd
    let hexData = hash.data(using: String.Encoding.utf8)
    let signature = hexData?.base64EncodedString()
    print(signature!)
}
//Produces Y2EwZmZkMzQyMDI2ZTQ4MjMwMThhMjRhZjM0M2YyNTFlMDU2OTMzMTE0YzE5YjMwYmMyZGNlNTY3NGU3NGZjZA==

Am I being stupid here... or should these two values be the same, as it is the same encryption algorithm, and the same key for the same value. As far as I can tell the C# example produces the 'correct' result, as a webservice that is consuming a value produced with that example works fine, but the value that the swift version produces is failing.


回答1:


The issue here seems to be a difference in the base64 strings between the given swift solution and then C# solution.

The output of the hash algorithm was the same at a byte level but it was being manipulated through various string conversions before being returned.

The function

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

Which is part of the solution converts the raw hashed data to a string, which is then converted back to a data object in the calling class, which is then cast into a base64 string to be returned. As we are getting a base64 string of of the string that was returned and not the raw bytes, I think this is where the issue was.

By changing the hmac code from the solution to this, we can cast the raw output of the has to a base64 string and avoid the other steps. This matches the C# value.

func hmac(algorithm: CryptoAlgorithm, key: String) -> String {
    let str = self.cString(using: String.Encoding.utf8)
    let strLen = Int(self.lengthOfBytes(using: String.Encoding.utf8))
    let digestLen = algorithm.digestLength
    let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
    let keyStr = key.cString(using: String.Encoding.utf8)
    let keyLen = Int(key.lengthOfBytes(using: String.Encoding.utf8))
        
    CCHmac(algorithm.HMACAlgorithm, keyStr!, keyLen, str!, strLen, result)
    let a = UnsafeMutableBufferPointer(start: result, count: digestLen)
    let b = Data(a)        
    result.deallocate()        
    let digest = b.base64EncodedString()        
    return digest
}


来源:https://stackoverflow.com/questions/62625832/hmac-sha256-in-c-sharp-vs-hmac-sha256-in-swift-dont-match

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!