Created
April 26, 2020 17:00
-
-
Save IamSaurav/623a41d3331c151cad5750b1ec422bd2 to your computer and use it in GitHub Desktop.
Create sha256 hash from different formats like Data, String, SecCertificate.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func sha256(_ certificate: SecCertificate) -> String? { | |
let certData = SecCertificateCopyData(certificate) as Data | |
let certStr = certData.base64EncodedString() | |
return sha256(certStr) | |
} | |
func sha256(_ data: Data) -> Data? { | |
guard let dataBuffer = NSMutableData(length: Int(CC_SHA256_DIGEST_LENGTH)) else { return nil } | |
CC_SHA256((data as NSData).bytes, CC_LONG(data.count), dataBuffer.mutableBytes.assumingMemoryBound(to: UInt8.self)) | |
return dataBuffer as Data | |
} | |
func sha256(_ str: String) -> String? { | |
guard let data = str.data(using: String.Encoding.utf8), let shaData = sha256(data) | |
else { return nil } | |
return shaData.base64EncodedString() | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment