Apple’s CommonCrypto/CommonHMAC.h is not available in Swift on Linux. Previously, I had a function for returning the SHA256 of a string using CommonCrypto:

static func sha256(string: String) -> String? {
    if let data = string.data(using: .utf8) {
        var hash = [UInt8](repeating: 0,  count: Int(CC_SHA256_DIGEST_LENGTH))
        data.withUnsafeBytes {
            _ = CC_SHA256($0, CC_LONG(data.count), &hash)
        }
        let result = Data(bytes: hash)
        return result.base64EncodedString()
    }
    return nil
}

Since CommonCrypto isn’t available on Linux, I needed a new way to generate SHA256. For my Evolizer server I’m using the Perfect Swift Framework. This framework happens to have extensive cross platform crypto utilities. Using the Perfect libraries my function became:

static func sha256(string: String) -> String? {
    if let encoded = string.digest(.sha256)?.encode(.base64) {
        return String(validatingUTF8: encoded)
    }
    return nil
}