How to get SHA1 from a String in Swift?

5

I know that the SHA1 object exists but I'm still learning the syntax, so, my beginner question is, given a simple string:

var greeting = "Hello!"

How to get SHA1 from greeting to Swift ?

    
asked by anonymous 27.07.2014 / 14:21

1 answer

5

You can use Apple's encryption framework. Add #import <CommonCrypto/CommonCrypto.h> to your class that bridges Objective-C and Swift (% with%). So you can use the code below:

extension String {
    func sha1() -> String! {
        let str = self.cStringUsingEncoding(NSUTF8StringEncoding)
        let strLen = CUnsignedInt(self.lengthOfBytesUsingEncoding(NSUTF8StringEncoding))
        let digestLen = Int(CC_SHA1_DIGEST_LENGTH)
        let result = UnsafePointer<CUnsignedChar>.alloc(digestLen)

        CC_SHA1(str!, strLen, result)

        var hash = NSMutableString()
        for i in 0..<digestLen {
            hash.appendFormat("%02x", result[i])
        }

        result.destroy()
        return String(hash)
    }
}

EDIT: In the latest version of Xcode the *-Bridging-Header.h method receives different parameters. It is necessary to change the type of variable CC_SHA1 to result

let result = UnsafeMutablePointer<UInt8>.alloc(digestLen)

And for example, to use:

var greeting = "Hello!"
NSLog("%@", greeting.sha1())

If you want to check out the project by running the latest version of Xcode 6, just take a look at the example I put in GitHub: link

    
27.07.2014 / 20:38