2
    func SHA256() -> String {

    let data = self.data(using: String.Encoding.utf8)
    let res = NSMutableData(length: Int(CC_SHA256_DIGEST_LENGTH))
    CC_SHA256((data! as NSData).bytes, CC_LONG(data!.count), UnsafeMutablePointer(res!.mutableBytes))
    let hashedString = "\(res!)".replacingOccurrences(of: "", with: "").replacingOccurrences(of: " ", with: "")
    let badchar: CharacterSet = CharacterSet(charactersIn: "\"<\",\">\"")
    let cleanedstring: String = (hashedString.components(separatedBy: badchar) as NSArray).componentsJoined(by: "")
    return cleanedstring

}

I am using this function to encrypt strings it was working fine in swift 2, now its not working in swift 3.0enter image description here

samad5353
  • 381
  • 1
  • 5
  • 18
  • http://stackoverflow.com/questions/25388747/sha256-in-swift ? – Larme Oct 07 '16 at 15:45
  • Or perhaps this one for a String to String function: http://stackoverflow.com/questions/25761344/how-to-crypt-string-to-sha1-with-swift, it can easily be adapted to SHA256. – Martin R Oct 07 '16 at 15:55
  • SHA256, infact all hash functions are not encryption, they are one-way hash functions. – zaph Oct 08 '16 at 01:52

3 Answers3

8

Perfect solution Swift 3+:

 extension String {

    // MARK: - SHA256
    func get_sha256_String() -> String {
        guard let data = self.data(using: .utf8) else {
            print("Data not available")
            return ""
        }
        return getHexString(fromData: digest(input: data as NSData))
    }

    private func digest(input : NSData) -> NSData {
        let digestLength = Int(CC_SHA256_DIGEST_LENGTH)
        var hashValue = [UInt8](repeating: 0, count: digestLength)
        CC_SHA256(input.bytes, UInt32(input.length), &hashValue)
        return NSData(bytes: hashValue, length: digestLength)
    }

    private  func getHexString(fromData data: NSData) -> String {
        var bytes = [UInt8](repeating: 0, count: data.length)
        data.getBytes(&bytes, length: data.length)

        var hexString = ""
        for byte in bytes {
            hexString += String(format:"%02x", UInt8(byte))
        }
        return hexString
    }
}

How to use:

let desiredSHA256 = "yourString".get_sha256_String()
Bhuvan Bhatt
  • 3,276
  • 2
  • 18
  • 23
5
func sha256(string: String) -> Data? {
    guard let messageData = string.data(using:String.Encoding.utf8) else { return nil; }
   var digestData = Data(count: Int(CC_SHA256_DIGEST_LENGTH))

    _ = digestData.withUnsafeMutableBytes {digestBytes in
        messageData.withUnsafeBytes {messageBytes in
            CC_SHA256(messageBytes, CC_LONG(messageData.count), digestBytes)
        }
    }
    return digestData
}

Example:

let testString = "sha me"
print("testString: \(testString)")
let shaData = sha256(string: testString)
let shaHex = shaData!.map { String(format: "%02hhx", $0) }.joined()
print("shaHex: \(shaHex)")

Output:

testString: sha me
shaData: a60e0eee 30a3a4f1 c4f8b93f 16ad22cb 0339447b 1653f331 edbda55f eee00789

What is new is the .withUnsafeMutableBytes closure.

zaph
  • 111,848
  • 21
  • 189
  • 228
4
func SHA256() -> String {

    let data = self.data(using: String.Encoding.utf8)
    let res = NSMutableData(length: Int(CC_SHA256_DIGEST_LENGTH))
    CC_SHA256(((data! as NSData)).bytes, CC_LONG(data!.count), res?.mutableBytes.assumingMemoryBound(to: UInt8.self))
    let hashedString = "\(res!)".replacingOccurrences(of: "", with: "").replacingOccurrences(of: " ", with: "")
    let badchar: CharacterSet = CharacterSet(charactersIn: "\"<\",\">\"")
    let cleanedstring: String = (hashedString.components(separatedBy: badchar) as NSArray).componentsJoined(by: "")
    return cleanedstring

}

Replaced CC_SHA256((data! as NSData).bytes, CC_LONG(data!.count), UnsafeMutablePointer(res!.mutableBytes))

samad5353
  • 381
  • 1
  • 5
  • 18