NSString casting for unsigned char *

I am trying to use a function that has the following signature to sign an HTTP request:

extern void hmac_sha1(const unsigned char *inText, int inTextLength, unsigned char* inKey, const unsigned int inKeyLength, unsigned char *outDigest); 

And this is the method I wrote to use it:

 - (NSString *)sign: (NSString *)stringToSign { NSString *secretKey = @"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; const unsigned char *inText = (unsigned char *)[stringToSign UTF8String]; int inTextLength = [stringToSign length]; unsigned char *inKey = (unsigned char *)[secretKey UTF8String]; const unsigned int inKeyLength = (unsigned int)[secretKey length]; unsigned char *outDigest; hmac_sha1(inText, inTextLength, inKey, inKeyLength, outDigest); NSString *output = [NSString stringWithUTF8String:(const char *)outDigest]; return output; } 

The problem is that I am sure that this is not the way I should do this casting, since inside this hmac_sha1 function I get an EXC_BAD_ACCESS exception.

Since I am new to Objective-C and have no experience in C (surprise!), I really don't know what to look for. Any tips on how I can solve this?

Thanks in advance!

BTW, I got a link for this function https://stackoverflow.com/a/464626/

+1
objective-c iphone
source share
3 answers

It seems that the problem is not with casting, but with outDigest . The fifth argument to hmac_sha1 should point to an already allocated buffer of 20 bytes (I think).

If you change the line that says

 unsigned char *outDigest; 

to tell

 #define HMACSHA1_DIGEST_SIZE 20 void *outDigest = malloc(HMACSHA1_DIGEST_SIZE); 

This should crash inside hmac_sha1 .

Then you had the problem of converting data from outDigest to NSString . It seems that hmac_sha1 will put 20 bytes of random data in outDigest , and not at the zero-end of a UTF-8 string, so stringWithUTF8String: will not work. Instead, you can use something like this if you need to return an NSString :

 NSString *output = [[NSString alloc] initWithBytesNoCopy:outDigest length:HMACSHA1_DIGEST_SIZE encoding:NSASCIIStringEncoding freeWhenDone:YES]; 

I don't think NSString really the right type for the digest, so it might be worth changing your method to return NSData if you can.

+3
source share

This was not part of your question, but, nevertheless, this is a mistake, you should not use -length to get the number of bytes of a UTF8 string. This method returns the number of Unicode characters in a string, not the number of bytes. You want -lengthOfBytesUsingEncoding:

 NSUInteger byteCount = [stringToSign lengthOfBytesUsingEncoding:NSUTF8StringEncoding]; 

Also keep in mind that the result does not account for the terminating NULL character.

+2
source share

Are you sure you do not need to allocate some memory for outDigest before calling hmac_sha1 ? Since you are passing a pointer, not a pointer to a pointer, there is no way that memory can be allocated inside a routine.

+1
source share

All Articles