Saltar al contenido

HMAC SHA256 en Swift 4

Te sugerimos que revises esta respuesta en un ambiente controlado antes de enviarlo a producción, un saludo.

Solución:

He estado usando esto:

import Foundation

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.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(capacity: digestLen)

        return digest
    

    private func stringFromResult(result: UnsafeMutablePointer, length: Int) -> String 
        let hash = NSMutableString()
        for i in 0..

Tendrás que agregar #import a su encabezado de puente Objective-C.

Fuente: @thevalyreangroup en este hilo de github

Lo estás haciendo mal con CryptoSwift.

Para los futuros lectores, he aquí cómo hacerlo:

let result = try! HMAC(key: key, variant: .sha256).authenticate(message.bytes)

Si apunta a iOS 13.0+ o macOS 10.15+, use CryptoKit de Apple

import CryptoKit

let secretString = "my-secret"
let key = SymmetricKey(data: secretString.data(using: .utf8)!)

let string = "An apple a day keeps anyone away, if you throw it hard enough"

let signature = HMAC.authenticationCode(for: string.data(using: .utf8)!, using: key)
print(Data(signature).map  String(format: "%02hhx", $0) .joined()) // 1c161b971ab68e7acdb0b45cca7ae92d574613b77fca4bc7d5c4effab89dab67

Comentarios y puntuaciones

¡Haz clic para puntuar esta entrada!
(Votos: 0 Promedio: 0)



Utiliza Nuestro Buscador

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *