Breaking News
Home / iOS / iOS Snippets / How to compute SHA1 digest for NSString?

How to compute SHA1 digest for NSString?

Computing SHA1 (Message Digest). The following is implemented as extension to NSString.

  1. //
  2. //  NSString+Hashing.h
  3.  
  4. #import <Foundation/Foundation.h>
  5.  
  6. @interface NSString (Hashing)
  7. (NSString *)sha1;
  8. @end
  9.  
  10. //
  11. //  NSString+Hashing.m
  12.  
  13. #import "NSString+Hashing.h"
  14. #import <CommonCrypto/CommonDigest.h>
  15.  
  16. @implementation NSString (Hashing)
  17.  
  18. (NSString *)sha1 {
  19.         NSData *data = [self dataUsingEncoding: NSUTF8StringEncoding];
  20.         uint8_t digest[CC_SHA1_DIGEST_LENGTH];
  21.  
  22.         CC_SHA1(data.bytes, data.length, digest);
  23.  
  24.         NSMutableString *output = [NSMutableString stringWithCapacity: CC_SHA1_DIGEST_LENGTH * 2];
  25.  
  26.         for (int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++) {
  27.                 [output appendFormat: @"%02x", digest[i]];
  28.         }
  29.  
  30.         return output;
  31. }
  32.  
  33. @end
[pb_builder]

Check Also

EKCalendar – That account does not allow calendars to be added or removed

Usecase When I am trying to create a new Calendar programmatically using the EventKit API …

Advertisment ad adsense adlogger