How to get SHA1 from a String in Swift?

Asked

Viewed 323 times

5

I know there’s an object SHA1 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 in Swift?

1 answer

5


you can use Apple’s encryption framework. Add #import <CommonCrypto/CommonCrypto.h> in its class that bridges the gap between Objective-C and Swift (*-Bridging-Header.h). 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 method CC_SHA1 receive different parameters. You need to change the type of the variable result for a UnsafeMutablePointer<UInt8>

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 running on the latest version of Xcode 6, just take a look at the example I put on Github: https://github.com/xdoug/Swift-SHA1

  • oi @Douglas-Erreira I am using version 6.0.1 of Xcode available in the App Store and following the instructions to create the Swift-Objective C bridge of this link I noted that the option described in the "Importing Objective-C into Swift" session was not offered. What would be the alternative ?

  • 1

    I’ve had this problem once, you can manually create the Bridging Header. Add a file from header with the name [SeuProjeto]-Bridging-Header.h. No build Settings of your project, look for Swift Compiler – Code Generationand then Objective-C Bridging Header and then you put the path of your file header (SeuProjeto/SeuProjeto-Bridging-Header.h), for example.

  • Thanks @Douglas-Ferreira. I created bridge but there was an error in your Swift code. It has to do with my Xcode version. The error was this: 'UnsafePointer<CUnsignedChar>.Type' does not have a member named 'alloc' on the line : let result = UnsafePointer<CUnsignedChar>.alloc(digestLen). Do you have any suggestions ?

  • I found an argument about this problem in this OS post. There are some suggested approaches. Which one do you think best ?

  • Apple changed the constructor of CC_SHA1 in one of the updates of Xcode6/Swift. Adjusting to the correct shape would let result = UnsafeMutablePointer<UInt8>.alloc(digestLen). I’ll update my answer.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.