Objective-C: Creating sha1 byte array
I solved an interesting problem that I needed to create a SHA1 hash, but the result had to be a byte array.
I needed to do in Objective-C function that will return the same result as the following C# code:
Objective-C
1 |
System.Security.Cryptography.SHA1.Create().ComputeHash(Encoding.Unicode.GetBytes("password")) |
The main problem is in selecting the correct encoding, and convert input string. Here is final function:
Objective-C
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
- (NSMutableArray *)calculateSHA:(NSString *)yourString { //create char const char *cstr = [yourString cStringUsingEncoding:NSUnicodeStringEncoding]; //create byte array NSData *data = [NSData dataWithBytes:cstr length:yourString.length*2]; //allocate digest uint8_t digest[CC_SHA1_DIGEST_LENGTH]; //hash byte array CC_SHA1(data.bytes, data.length, digest); //create mutable array NSMutableArray *array = [[[NSMutableArray alloc] init] autorelease]; for (int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++){ //formatter NSNumberFormatter * f = [[NSNumberFormatter alloc] init]; [f setNumberStyle:NSNumberFormatterDecimalStyle]; //add number of byte into array NSNumber * myNumber = [f numberFromString:[NSString stringWithFormat:@"%d", digest[i]]]; [f release]; //end formatter [array addObject:myNumber]; } return array; } |
Posted on 9 May 2013