4

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?

Matthew N
  • 359
  • 4
  • 14

1 Answers1

7

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>
Vini App
  • 7,339
  • 2
  • 26
  • 43