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?
Asked
Active
Viewed 7,303 times
1 Answers
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
-
-
Please check my updated answer. You have import `CommonCrypto` in your bridging header. – Vini App Oct 17 '17 at 16:55