Reputation: 655
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?
Upvotes: 1
Views: 312
Reputation: 655
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
}
Upvotes: 1