How can I create a SHA1 from a NSString
.
Let\'s say the NSString is set up as:
NSString *message = @\"Message\";
I can
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 <CommonCrypto/CommonCrypto.h>
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..<CC_SHA1_DIGEST_LENGTH
{
selfAsSha1 += String(format: "%02x", digest[Int(index)])
}
}
return selfAsSha1
}
}
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 :)