samad5353 samad5353 - 1 month ago 22
iOS Question

Sha 256 Encryption syntax error in swift 3.0

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

Answer
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))

Comments