0

Ok I have tried dozens of cryptography attempts to replicate the answer in:

String: 1538831506GET/v2/user

key: R11ScShruvOGBkwMhxCPJEmWLKnwpeLf

Expected Result: b4f28c23d9195a3903eeb8aa6214f632f415bbdfbfa2c58f08dad96529bfbdc2

Convert online to SHA256

However nothing seems to get the same answer. I have tried CryptoSwift, CommonCrypto (objective-c), IDZSwiftCommonCrypto.. and nothing seems to work.

Here is some sample code:

    func getHMacSHA256(forMessage message: String, key: String) -> String? {


    //CommonCrypto
    let str = message
    let hmac_sha256 = str.hmac(algorithm: .sha256, key: key)
    print(hmac_sha256)
    let hex: String = hmac_sha256.unicodeScalars.filter { $0.isASCII }
        .map { String(format: "%X", $0.value) }
        .joined()
    print(hex)

    //IDZSwiftCommonCrypto
    let hMacVal = HMAC(algorithm: HMAC.Algorithm.sha256, key: key).update(string: message)?.final()


    if let encryptedData = hMacVal {
        let decData = NSData(bytes: encryptedData, length: Int(encryptedData.count))
        let base64String = decData.base64EncodedString(options: .lineLength64Characters)
        let hexString = (decData as Data).hexEncodedString()
        print("base64String: \(base64String)")
        print("hexString: \(hexString)")
        return hexString
    } else {
        return nil
    }
}
jimijon
  • 2,046
  • 1
  • 20
  • 39
  • SHA256 is a hashing algorithm. The only input is the text to be hashed. – Avi Oct 07 '18 at 16:13
  • In my framework, I use the implementation from SwiftPM. – Avi Oct 07 '18 at 16:13
  • This: https://stackoverflow.com/a/44736926/1187415 does exactly what you want – Martin R Oct 07 '18 at 16:55
  • It did not give me the same answer. Using the linked answer I got: signature String "NDlhZGY5N2M0ODMxNDhiODkxOWY3MWQ2OWU5MzNmMzRlYmNkNTYxZWUzYWY5ZTE3\r\nMWI5OWJmZWFkN2FhMTAzYg==" – jimijon Oct 07 '18 at 17:02
  • @jimijon: It does for me: `let message = "1538831506GET/v2/user"; let key = "R11ScShruvOGBkwMhxCPJEmWLKnwpeLf" ; print(message.hmac(algorithm: .SHA256, key: key))` prints "b4f28c23d9195a3903eeb8aa6214f632f415bbdfbfa2c58f08dad96529bfbdc2" – Martin R Oct 07 '18 at 17:20
  • Evidently I used the wrong one. your example works, this did not: let signature = sha256(StringToSign : "1538831506GET/v2/user", secretKey : "R11ScShruvOGBkwMhxCPJEmWLKnwpeLf") – jimijon Oct 07 '18 at 17:54
  • @jimijon: That produces the result as Base64 encoded string, instead of the hex encoding. – Martin R Oct 07 '18 at 18:03

0 Answers0