Unsigned Char Array to Hex Representation NSString - objective-c

I have an unsigned char array and I want to convert it to hex NSString, currently I do it in the following way:
unsigned char result[16];
// Fill the array
NSString *myHexString = [NSString stringWithFormat: #"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
result[0], result[1], result[2], result[3],
result[4], result[5], result[6], result[7],
result[8], result[9], result[10], result[11],
result[12], result[13], result[14], result[15]
]];
Is there a better way to built-in function that achieves that?

How about this?
NSMutableString *hex = [NSMutableString string];
for (int i=0; i<16; i++)
[hex appendFormat:#"%02x", result[i]];
// And if you insist on having the hex in an immutable string:
NSString *immutableHex = [NSString stringWithString:hex];
You can also turn the code into a category to keep things nice:
#implementation NSString (Hex)
+ (NSString*) hexStringWithData: (unsigned char*) data ofLength: (NSUInteger) len
{
NSMutableString *tmp = [NSMutableString string];
for (NSUInteger i=0; i<len; i++)
[tmp appendFormat:#"%02x", data[i]];
return [NSString stringWithString:tmp];
}
#end
Then your code boils down to:
unsigned char result[16] = {…};
NSString *hexString = [NSString hexStringWithData:result ofLength:16];
I think that’s about as nice as it gets.

Related

XOR'ing two hex values stored as an NSString?

here is yet another silly question from me!
NSString *hex1 = #"50be4f3de4";
NSString *hex2 = #"30bf69a299";
/* some stuff like result = hex1^hex2; */
NSString *result = #"6001269f7d";
I have a hex value as a string, stored in two diff. variables. i need to Xor them and the result should be in another string variables?
i tried them by converting string --> NSData --> bytes array --> xor'ing them ...but i have no success.....
thank you in advance...
You have to convert every character to Base16(for hexadecimal) format first.Then you should proceed with XORing those characters.You can use the strtol() function to achieve this purpose.
NSString *hex1 = #"50be4f3de4";
NSString *hex2 = #"30bf69a299";
NSMutableArray *hexArray1 = [self splitStringIntoChars:hex1];
NSMutableArray *hexArray2 = [self splitStringIntoChars:hex2];
NSMutableString *str = [NSMutableString new];
for (int i=0; i<[hexArray1 count]; i++ )
{
/*Convert to base 16*/
int a=(unsigned char)strtol([[hexArray1 objectAtIndex:i] UTF8String], NULL, 16);
int b=(unsigned char)strtol([[hexArray2 objectAtIndex:i] UTF8String], NULL, 16);
char encrypted = a ^ b;
NSLog(#"%x",encrypted);
[str appendFormat:#"%x",encrypted];
}
NSLog(#"%#",str);
Utility method that i used to split characters of the string
-(NSMutableArray*)splitStringIntoChars:(NSString*)argStr{
NSMutableArray *characters = [[NSMutableArray alloc]
initWithCapacity:[argStr length]];
for (int i=0; i < [argStr length]; i++)
{
NSString *ichar = [NSString stringWithFormat:#"%c", [argStr characterAtIndex:i ]];
[characters addObject:ichar];
}
return characters;
}
Hope it helps!!

How to calculate the hash MD5 of each content of a NSMutableArray?

I have this:
NSString *string1 = ...;
NSString *string2 = ...;
NSMutableArray *array = [NSMutableArray alloc]inithWithObjects:string1, string2]autorelease];
How do I calculate the MD5 hash (or other more appropriate hash) for each content of the array, for further comparisons?
Thanks!
You can use this method on every string of your array:
- (NSString*)md5HexDigest:(NSString*)input {
const char* str = [input UTF8String];
unsigned char result[CC_MD5_DIGEST_LENGTH];
CC_MD5(str, strlen(str), result);
NSMutableString *ret = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH*2];
for(int i = 0; i<CC_MD5_DIGEST_LENGTH; i++) {
[ret appendFormat:#"%02x",result[i]];
}
return ret;
}
Do not forget to include:
#import <CommonCrypto/CommonDigest.h>

How to SHA hash in cocoa/iOS

Given the message and the salt how can I encode it returning the hashed string?
I need reproduce the php function:
hash_hmac('sha256','message','salt');
Thanks
Found the answer:
#import <CommonCrypto/CommonHMAC.h>
-(NSString *) hashString :(NSString *) data withSalt: (NSString *) salt {
const char *cKey = [salt cStringUsingEncoding:NSUTF8StringEncoding];
const char *cData = [data cStringUsingEncoding:NSUTF8StringEncoding];
unsigned char cHMAC[CC_SHA256_DIGEST_LENGTH];
CCHmac(kCCHmacAlgSHA256, cKey, strlen(cKey), cData, strlen(cData), cHMAC);
NSString *hash;
NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA256_DIGEST_LENGTH * 2];
for(int i = 0; i < CC_SHA256_DIGEST_LENGTH; i++)
[output appendFormat:#"%02x", cHMAC[i]];
hash = output;
return hash;
}

NSString get -characters

I want to get the characters of an NSString. Like this:
NSString *data;
const char * typein = [[data characters] UTF8String];
But obviously NSString won't respond to -characters. How do I get the characters of NSString?
thanks,
Elijah
You can use this function:
for(int i =0 ;i<[myString length]; i++) {
char character = [myString characterAtIndex:i];
}
or
NSString *str = #"astring";
const char *cString = [str UTF8String];
If you just want to get a cString from the NSString just call UTF8String as you are already doing and then iterate the array.

Trying to Write NSString sha1 function, but it's returning null

I have the following Objective-C function:
+(NSString *)stringToSha1:(NSString *)str{
NSMutableData *dataToHash = [[NSMutableData alloc] init];
[dataToHash appendData:[str dataUsingEncoding:NSUTF8StringEncoding]];
unsigned char hashBytes[CC_SHA1_DIGEST_LENGTH];
CC_SHA1([dataToHash bytes], [dataToHash length], hashBytes);
NSData *encodedData = [NSData dataWithBytes:hashBytes length:CC_SHA1_DIGEST_LENGTH];
[dataToHash release];
NSString *encodedStr = [NSString stringWithUTF8String:[encodedData bytes]];
//NSString *encodedStr = [[NSString alloc] initWithBytes:[encodedData bytes]
// length:[encodedData length] encoding: NSUTF8StringEncoding];
NSLog(#"String is %#", encodedStr);
return encodedStr;
}
What I'm trying to do is take an NSString and SHA1 encode it. That part seems to be working, I think where I am falling over is in how to convert the NSData object back to a legible string. If I use UTF8 encoding I get blank, if I say ASCII I get weird characters. What I really want is the hex string, but I have no idea how to get it. This is using the iPhone 3.0 SDK.
At the moment any String I pass in comes back out NULL.
My version of SHA1 function (simplier):
- (NSString *)sha1:(NSString *)str {
const char *cStr = [str UTF8String];
unsigned char result[CC_SHA1_DIGEST_LENGTH];
CC_SHA1(cStr, strlen(cStr), result);
NSString *s = [NSString stringWithFormat:
#"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
result[0], result[1], result[2], result[3], result[4],
result[5], result[6], result[7],
result[8], result[9], result[10], result[11], result[12],
result[13], result[14], result[15],
result[16], result[17], result[18], result[19]
];
return s;
}
And MD5:
- (NSString *)md5:(NSString *)str {
const char *cStr = [str UTF8String];
unsigned char result[CC_MD5_DIGEST_LENGTH];
CC_MD5(cStr, strlen(cStr), result);
NSString *s = [NSString stringWithFormat:
#"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
result[0], result[1], result[2], result[3], result[4],
result[5], result[6], result[7],
result[8], result[9], result[10], result[11], result[12],
result[13], result[14], result[15]
];
return s;
}
Short answer: turn on gcc warnings (-Wall).
Long answer:
NSMutableData *dataToHash = [[NSMutableData alloc] init];
[dataToHash appendData:[str dataUsingEncoding:NSUTF8StringEncoding]];
is broken: You try to use a C string where an NSData argument is expected. Use
NSMutableData *dataToHash = [str dataUsingEncoding:NSUTF8StringEncoding];
instead.
The rest of the method takes the SHA1 buffer and tries interpret this data as an UTF-8 C string, which might crash or give any unexpected result. First, the buffer is not a UTF-8 string. Secondly, it's not null terminated.
What you want is to convert the SHA1 to a base 64 or similar string. Here's a nice post about how to do that.
This is what I ended up with, the next step would be to convert it to be a Category of NSString instead of a static method in a helper class:
+(NSString *)stringToSha1:(NSString *)str{
const char *s = [str cStringUsingEncoding:NSASCIIStringEncoding];
NSData *keyData = [NSData dataWithBytes:s length:strlen(s)];
// This is the destination
uint8_t digest[CC_SHA1_DIGEST_LENGTH] = {0};
// This one function does an unkeyed SHA1 hash of your hash data
CC_SHA1(keyData.bytes, keyData.length, digest);
// Now convert to NSData structure to make it usable again
NSData *out = [NSData dataWithBytes:digest length:CC_SHA1_DIGEST_LENGTH];
// description converts to hex but puts <> around it and spaces every 4 bytes
NSString *hash = [out description];
hash = [hash stringByReplacingOccurrencesOfString:#" " withString:#""];
hash = [hash stringByReplacingOccurrencesOfString:#"<" withString:#""];
hash = [hash stringByReplacingOccurrencesOfString:#">" withString:#""];
NSLog(#"Hash is %# for string %#", hash, str);
return hash;
}
glycol,
You will need to define your CC_SHA1_DIGEST_LENGTH constant, probably to 20, as that's the length of an SHA-1 digest according to the NIST spec at http://www.itl.nist.gov/fipspubs/fip180-1.htm