Skip to content

Instantly share code, notes, and snippets.

@davidleee
Created April 13, 2018 09:20
Show Gist options
  • Save davidleee/5ff40c81d3902d5feb3098f567409825 to your computer and use it in GitHub Desktop.
Save davidleee/5ff40c81d3902d5feb3098f567409825 to your computer and use it in GitHub Desktop.
Getting all kinds of crypted string from the original string (keep updating...)
// You should put "#import <CommonCrypto/CommonHMAC.h>" in the bridge header before using these code
import Foundation
extension String {
func sha256() -> String {
if let stringData = self.data(using: String.Encoding.utf8) as NSData? {
let digest = digestSHA256(source: stringData)
var bytes = [UInt8](repeating: 0, count: digest.length)
digest.getBytes(&bytes, length: digest.length)
var hexString = ""
for byte in bytes {
hexString += String(format: "%02x", UInt8(byte))
}
return hexString
} else {
return ""
}
}
private func digestSHA256(source: NSData) -> NSData {
let length = Int(CC_SHA256_DIGEST_LENGTH)
var hash = [UInt8](repeating: 0, count: length)
CC_SHA256(source.bytes, UInt32(source.length), &hash)
return NSData(bytes: hash, length: length)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment