Skip to content

Instantly share code, notes, and snippets.

@maxhuk
Created April 9, 2013 12:54
Show Gist options
  • Save maxhuk/5345488 to your computer and use it in GitHub Desktop.
Save maxhuk/5345488 to your computer and use it in GitHub Desktop.
Common hashing algorithms on top of NSString.
//
// NSString+Hash.h
//
// Created by Maksym Huk on 10/10/12.
// Copyright (c) 2012 Maksym Huk. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface NSString (Hash)
- (NSString*)hashSHA1;
- (NSString*)hashMD5;
@end
//
// NSString+Hash.m
//
// Created by Maksym Huk on 10/10/12.
// Copyright (c) 2012 Maksym Huk. All rights reserved.
//
#import <CommonCrypto/CommonCrypto.h>
#import "NSString+Hash.h"
@implementation NSString (Hash)
- (NSString*)hashSHA1
{
const char *cstr = [self cStringUsingEncoding:NSUTF8StringEncoding];
NSData *data = [NSData dataWithBytes:cstr length:self.length];
uint8_t digest[CC_SHA1_DIGEST_LENGTH];
CC_SHA1(data.bytes, data.length, digest);
NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];
for(int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++)
[output appendFormat:@"%02x", digest[i]];
return output;
}
- (NSString *)hashMD5
{
const char *cStr = [self UTF8String];
unsigned char digest[16];
CC_MD5( cStr, strlen(cStr), digest ); // This is the md5 call
NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
[output appendFormat:@"%02x", digest[i]];
return output;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment