Hello i need to implement hash_hmac php method to swift and try like this:
var hexString = ""
var result: [CUnsignedChar]
if let cKey = keyStr.cString(using: String.Encoding.utf8),
let cData = messageStr.cString(using: String.Encoding.utf8)
{
let algo = CCHmacAlgorithm(kCCHmacAlgSHA256)
result = Array(repeating: 0, count: Int(CC_SHA256_DIGEST_LENGTH))
CCHmac(algo, cKey, cKey.count, cData, cData.count, &result)
} else {
fatalError("ERROR...")
}
for byte in result {
hexString += String(format:"%2hhx", UInt8(byte))
}
print(hexString)
but this is not simulated like PHP exactly.
And i tried this code :
let secretData : Data = messageStr.data(using: .utf8)!
let signatureData : Data = keyStr.data(using: .utf8)!
let digest = UnsafeMutablePointer<UInt8>.allocate(capacity:Int(CC_SHA256_DIGEST_LENGTH))
var hmacContext = CCHmacContext()
CCHmacInit(&hmacContext, CCHmacAlgorithm(kCCHmacAlgSHA256), [UInt8](secretData), secretData.count)
CCHmacUpdate(&hmacContext, [UInt8](signatureData), [UInt8](signatureData).count)
CCHmacFinal(&hmacContext, digest)
let cryptData = Data(bytes: digest, count: Int(CC_SHA256_DIGEST_LENGTH))
macStr = cryptData.hexEncodedString()
But it does not work...
edit:
message: a3FQZHJ1Z0hnOFhpZ2xkWg==8v8Fs6LXKTJOha69tsvUew==
key: u6KuXJLIUwEUl7noY8J8H1ffDRwLC/5gjaWW1qTQ3hE=
swift output: 37987524d1a379d67b2bae0a1618296d48b7a1f058a3b5816bf8070cb2fdf2ec
php output: 30f39f78a24ae2e6037114708f97fae1f3fede8dabece012a12b6625f3329302