Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 982
Matthew N Avatar asked Mar 08 '23 19:03

Matthew N


1 Answers

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>
like image 95
Vini App Avatar answered Apr 22 '23 15:04

Vini App