Creating SHA1 Hash from NSString

前端 未结 7 1210
梦毁少年i
梦毁少年i 2020-12-23 19:57

How can I create a SHA1 from a NSString.

Let\'s say the NSString is set up as:

NSString *message = @\"Message\";

I can

7条回答
  •  感情败类
    2020-12-23 20:39

    It took me a while to port @hypercrypt solution to Swift so I decided to share it with others that might have the same problem.

    One important thing to note is that you need CommonCrypto library, but that library does not have Swift module. The easiest workaround is to import it in your bridging header:

    #import 
    

    Once imported there, you do not need anything else. Just use String extension provided:

    extension String
    {
        func sha1() -> String
        {
            var selfAsSha1 = ""
    
            if let data = self.dataUsingEncoding(NSUTF8StringEncoding)
            {
                var digest = [UInt8](count: Int(CC_SHA1_DIGEST_LENGTH), repeatedValue: 0)
                CC_SHA1(data.bytes, CC_LONG(data.length), &digest)
    
                for index in 0..

    Notice that my solution does not take effect of reserving capacity what NSMutableString has in original post. However I doubt anyone will see the difference :)

提交回复
热议问题