Matthew
Matthew

Reputation: 379

Creating SHA256 hash with swift4

I've done some looking around but i've only been able to find examples that use Objective-C to create SHA256 hashes. Is there a way to do this with only Swift4?

Upvotes: 4

Views: 7700

Answers (1)

Vini App
Vini App

Reputation: 7485

You can use like this :

func ccSha256(data: Data) -> Data {
    var digest = Data(count: Int(CC_SHA256_DIGEST_LENGTH))

    _ = digest.withUnsafeMutableBytes { (digestBytes) in
        data.withUnsafeBytes { (stringBytes) in
            CC_SHA256(stringBytes, CC_LONG(data.count), digestBytes)
        }
    }
    return digest
}

You can call like this :

let str = "givesomestringtoencode"
let data = ccSha256(data: str.data(using: .utf8)!)
print("sha256 String: \(data.map { String(format: "%02hhx", $0) }.joined())")

Add the below in bridging header file:

#import <CommonCrypto/CommonHMAC.h>

Upvotes: 7

Related Questions