简体   繁体   中英

How to pass key in HMAC as HEX Swift iOS

So I have this code to generate for HMAC-SHA1

let key = "foo".toSHA1()
let data = "bar"
var results = [CUnsignedChar](repeating: 0, count: Int(CC_SHA1_DIGEST_LENGTH))

CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA1), key, key.count, data, data.count, &results)

let hmacData:NSData = NSData(bytes: results, length: (Int(CC_SHA1_DIGEST_LENGTH)))

var bytes = [UInt8](repeating: 0, count: hmacData.length)
hmacData.getBytes(&bytes, length: hmacData.length)

var hexString = ""
for byte in bytes {
    hexString += String(format:"%02hhx", UInt8(byte))
}

print(hexString)

and this code for converting key string to SHA1

func toSHA1() -> String {
        let data = self.data(using: String.Encoding.utf8)!
        var digest = [UInt8](repeating: 0, count:Int(CC_SHA1_DIGEST_LENGTH))
        data.withUnsafeBytes {
            _ = CC_SHA1($0, CC_LONG(data.count), &digest)
        }
        let hexBytes = digest.map { String(format: "%02x", $0) }

        return hexBytes.joined()
    }

and the result is

faa3c04b058d38cecf1243421a596742a6cf1188

so using this onlineHMAC Generator outputs the same result. But my desired output should be

38b24d28d64f2459d42d1ecd1c9fa375ffeb369f

and I can achieve this by changing the Key type to HEX in the page that I provided.

So my problem now is how do I get the same output in my code? Do I need to convert key to hex?

Fixed it by passing digest as key instead of converting it to string.

Here's the updated code

let key = "foo".toSHA1()
let data = "bar"
var results = [CUnsignedChar](repeating: 0, count: Int(CC_SHA1_DIGEST_LENGTH))

CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA1), key, key.count, data, data.count, &results)

let hmacData:NSData = NSData(bytes: results, length: (Int(CC_SHA1_DIGEST_LENGTH)))

var bytes = [UInt8](repeating: 0, count: hmacData.length)
hmacData.getBytes(&bytes, length: hmacData.length)

var hexString = ""
for byte in bytes {
    hexString += String(format:"%02hhx", UInt8(byte))
}

print(hexString)


func toSHA1() -> [UInt8] {
        let data = self.data(using: String.Encoding.utf8)!
        var digest = [UInt8](repeating: 0, count:Int(CC_SHA1_DIGEST_LENGTH))
        data.withUnsafeBytes {
            _ = CC_SHA1($0, CC_LONG(data.count), &digest)
        }

        return digest
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM