2Aug/092
Secure Hashes
If your application requires generation of secure hashes, you can use the raw Crypto APIs. These are actually C calls and do not have nice Objective C objects to interface with. The code snippet below shows how this is done for SHA-1. The input is any NSString and the output is a hex-encoded NSString version of the hashcode. If you need other types of hashing besides SHA-1, then you will need to change the SHA1 names in the functions and constants.
+ (NSString*) getHash:(NSString *) text
{
NSData* myData =
[text dataUsingEncoding:NSStringEncodingConversionAllowLossy];
CC_SHA1_CTX ctx;
uint8_t * hashBytes = NULL;
NSData * hash = nil;
// Malloc a buffer to hold hash.
hashBytes = malloc( CC_SHA1_DIGEST_LENGTH * sizeof(uint8_t) );
memset((void *)hashBytes, 0x0, CC_SHA1_DIGEST_LENGTH);
// Initialize the context.
CC_SHA1_Init(&ctx);
// Perform the hash.
CC_SHA1_Update(&ctx, (void *)[myData bytes], [myData length]);
// Finalize the output.
CC_SHA1_Final(hashBytes, &ctx);
// Build up the SHA1 data.
hash = [NSData dataWithBytes:(const void *)hashBytes
length:(NSUInteger)CC_SHA1_DIGEST_LENGTH];
// if could not create, then exit otherwise clean up
if(hashBytes)
free(hashBytes);
else
return nil;
// now return this as an hex-encoded string
NSMutableString *stringBuffer = [NSMutableString
stringWithCapacity:([hash length] * 2)];
const unsigned char *dataBuffer = [hash bytes];
int i;
for (i = 0; i < [hash length]; ++i)
{
[stringBuffer appendFormat:@"%02X", (unsigned long)dataBuffer[i]];
}
return [[stringBuffer copy] autorelease];
}
One thing to note is the you need to include the following line:
#import <CommonCrypto/CommonDigest.h>
January 19th, 2010 - 21:57
Updated post to include the import statement.
January 25th, 2010 - 21:57
Updated post to fix typo on the if (hashbytes) – was always returning on success.