Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sha 256 Encryption syntax error in swift 3.0

Tags:

xcode

ios

swift3

    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

like image 476
samad5353 Avatar asked Dec 03 '25 13:12

samad5353


1 Answers

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()
like image 97
Bhuvan Bhatt Avatar answered Dec 05 '25 03:12

Bhuvan Bhatt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!