0

I have been trying to find out a native hashing for HMAC with SHA256, for a specific values message and here it is :

extension String {

    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 = Int(CC_SHA256_DIGEST_LENGTH)
        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(CCHmacAlgorithm(kCCHmacAlgSHA256), keyStr!, keyLen, str!, strLen, result)

        let digest = stringFromResult(result: result, length: digestLen)

        result.deallocate(capacity: digestLen)

        return digest
    }


    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)
    }

}

Now Looking at this situation i do the hashing but how can i make a reverse function to get the hashed value using the secret key ? I don't want to use any external library only

#import <CommonCrypto/CommonHMAC.h>.

Nata Mio
  • 2,168
  • 3
  • 22
  • 46
  • 1
    SHA is a *hashing algorithm,* not an encryption. The very purpose of (cryptographic) hashing algorithms is that you can *not* reverse them. – Martin R Oct 20 '16 at 11:03
  • The idea is that you perform the same hashing on the client and server and compare the hashed values in order to validate the message from the client. – Paulw11 Oct 20 '16 at 11:06
  • @MartinR, i have been told to hash for example the email : aa@bb.com. and send it to backend. now how does the backend will know the hashed values using the secret key ? so there must be a way to get the hashed value from secret key isn't it ? – Nata Mio Oct 20 '16 at 11:23
  • @NataMio: You *cannot* decrypt/reverse a hash. Perhaps Paulw11's comment above answers your question. – Martin R Oct 20 '16 at 11:27

0 Answers0