create a function that calculates the sha256 checksum of raw data in swift

You can use the built-in CommonCrypto library in Swift to easily generate the SHA256 checksum for raw data. Here's a sample function that takes in raw data in the form of Data type and returns its SHA256 checksum as a hexadecimal string:

main.swift
import CommonCrypto

func sha256(data: Data) -> String {
    var hash = [UInt8](repeating: 0, count: Int(CC_SHA256_DIGEST_LENGTH))
    data.withUnsafeBytes {
        _ = CC_SHA256($0.baseAddress, CC_LONG(data.count), &hash)
    }
    return hash.map({ String(format: "%02x", $0) }).joined()
}
293 chars
10 lines

To use this function, simply pass your raw data as a Data object:

main.swift
let rawData = "Hello world".data(using: .utf8)!
let checksum = sha256(data: rawData) // "b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9"
155 chars
3 lines

gistlibby LogSnag