0

I need to generate the same hash value as the site below. https://cryptii.com/pipes/hmac

If the key is aaaa and the message is a The expected hash value is e29f14beeb21a8ee1d1c3b8c2be4cf440584da4d46aff5bacb2ae9aa7deb3271.

But the result is 8c21ecf95763195811ac0513bfa42a29be13b9d895b896af45e115dde9bc7382

Below is my code I don't know what's wrong.

I am wasting 6 hours now... so PLEASE HELP ME... : (

import CommonCrypto
import CryptoKit

enum CryptoAlgorithm {
    case MD5, SHA1, SHA224, SHA256, SHA384, SHA512

    var HMACAlgorithm: CCHmacAlgorithm {
        var result: Int = 0
        switch self {
        case .MD5:      result = kCCHmacAlgMD5
        case .SHA1:     result = kCCHmacAlgSHA1
        case .SHA224:   result = kCCHmacAlgSHA224
        case .SHA256:   result = kCCHmacAlgSHA256
        case .SHA384:   result = kCCHmacAlgSHA384
        case .SHA512:   result = kCCHmacAlgSHA512
        }
        return CCHmacAlgorithm(result)
    }

    var digestLength: Int {
        var result: Int32 = 0
        switch self {
        case .MD5:      result = CC_MD5_DIGEST_LENGTH
        case .SHA1:     result = CC_SHA1_DIGEST_LENGTH
        case .SHA224:   result = CC_SHA224_DIGEST_LENGTH
        case .SHA256:   result = CC_SHA256_DIGEST_LENGTH
        case .SHA384:   result = CC_SHA384_DIGEST_LENGTH
        case .SHA512:   result = CC_SHA512_DIGEST_LENGTH
        }
        return Int(result)
    }
}

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 = algorithm.digestLength
        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(algorithm.HMACAlgorithm, keyStr!, keyLen, str!, strLen, result)

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

        result.deallocate()
        result.deinitialize(count: 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).lowercased()
    }
}

public extension Data {

    /**
     Method creates bytes array from given Data
     - Returns: Array of bytes
     */
    func bytesArray<T: ExpressibleByIntegerLiteral>() -> [T] {
        var bytes = Array<T>(repeating: 0, count: self.count)
        (self as NSData).getBytes(&bytes, length:self.count * MemoryLayout<T>.size)
        return bytes
    }
}

public extension String {
    /**
     Method creates bytes array from given String
     - Returns: Array of bytes
     */
    func bytesArray<T: ExpressibleByIntegerLiteral>() -> [T] {
        let data = self.data(using: String.Encoding.utf8)!
        return data.bytesArray()
    }
}

extension Data {
    struct HexEncodingOptions: OptionSet {
        let rawValue: Int
        static let upperCase = HexEncodingOptions(rawValue: 1 << 0)
    }

    func hexEncodedString(options: HexEncodingOptions = []) -> String {
        let format = options.contains(.upperCase) ? "%02hhX" : "%02hhx"
        return map { String(format: format, $0) }.joined()
    }
    var hexDescription: String {
        return reduce("") {$0 + String(format: "%02x", $1)}
    }
}
print("a".hmac(algorithm: .SHA256, key: Data("aaaa".utf8).hexEncodedString()))

print("a".hmac(algorithm: .SHA256, key: "aaaa").data(using: .utf8)?.base64EncodedString().description)
greatsk
  • 23
  • 3
  • 9

0 Answers0