Skip to content

Instantly share code, notes, and snippets.

@hisoka0917
Created April 26, 2018 08:39
Show Gist options
  • Save hisoka0917/9f92fb6e8c1908518763e1c8ab5e9707 to your computer and use it in GitHub Desktop.
Save hisoka0917/9f92fb6e8c1908518763e1c8ab5e9707 to your computer and use it in GitHub Desktop.
Swift String SHA256
extentsion String {
func SHA256() -> String {
if let stringData = self.data(using: .utf8) {
return self.hexStringFromData(input: digest(input: stringData as NSData))
} else {
return self
}
}
private func digest(input: NSData) -> NSData {
let digestLength = Int(CC_SHA256_DIGEST_LENGTH)
var hash = [UInt8](repeating: 0, count: digestLength)
CC_SHA256(input.bytes, UInt32(input.length), &hash)
return NSData(bytes: hash, length: digestLength)
}
private func hexStringFromData(input: NSData) -> String {
var bytes = [UInt8](repeating: 0, count: input.length)
input.getBytes(&bytes, length: input.length)
var hexString = ""
for byte in bytes {
hexString += String(format: "%02x", UInt8(byte))
}
return hexString
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment