HMAC<SHA256> in swift

I have 2 apps, I use HMAC for signature between apps. First App's minimum deployment target is 11.2 and it uses CryptoSwift for sending data to the second app while signing documents. But the Second app uses Apple's CryptoKit, and I get a signing error. Can I use different packages for HMAC Sha256 process?

Replies

HMAC is the same regardless of what library you use to implement it. I suspect that you have a bug in how you’re using one or the other library.

Note that you don’t need to use a third-party library to do HMAC on older systems. CommonCrypto has an HMAC API that works back to 10.4. The code pasted in below calculates the same MAC with both APIs, printing:

HMAC with SHA256: 23b99e335c025b1bae325e2b1961bd85f56d0120fc407662e9dcf53c995b03c2
<23b99e33 5c025b1b ae325e2b 1961bd85 f56d0120 fc407662 e9dcf53c 995b03c2>

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

import Foundation
import CryptoKit
import CommonCrypto

func main() {
    let data = [UInt8]("Hello Cruel World!".utf8)
    let key: [UInt8] = [
        0xFA, 0x71, 0x16, 0xB5, 0x3F, 0x40, 0x4B, 0xBC,
        0x99, 0xAE, 0x5B, 0x61, 0xFB, 0xC4, 0x55, 0x16,
    ]
    
    // Do the HMAC with Apple CryptoKit.
    
    let macACK = HMAC<SHA256>.authenticationCode(for: data, using: SymmetricKey(data: key))
    print(macACK)
    
    // Do the HMAC with CommonCrypto.
    
    var macCC = [UInt8](repeating: 0, count: Int(CC_SHA256_DIGEST_LENGTH))
    CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA256), key, key.count, data, data.count, &macCC);
    print((Data(macCC) as NSData).debugDescription)
}

main()