aepryus
aepryus

Reputation: 4825

Using CommonCrypto/CommonHMAC.h in Swift on Linux (Ubuntu) to get SHA256

I am trying to build:

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
}

using Swift Package Manager on Ubuntu 16.04. But the library is not being found. Is it available for Linux Swift? How do I point to it? If not, what is the recommend way to get a SHA256 in Linux Swift?

Upvotes: 1

Views: 753

Answers (1)

aepryus
aepryus

Reputation: 4825

I had been using Perfect for my Swift backend and it turns out they have many built in cross platform crypto utilities. The new function is:

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

Upvotes: 1

Related Questions