I am trying to encrypt a string with HMAC-SHA1 using CCHmac()
. I created an NSString
category
for this:
NSString+HMAC.h
#import <Foundation/Foundation.h>
#import <CommonCrypto/CommonDigest.h>
#import <CommonCrypto/CommonHMAC.h>
@interface NSString (HMAC)
- (NSString *)HMACSHA1WithKey:(NSString *)key;
@end
NSString+HMAC.m
#import "NSString+HMAC.h"
@implementation NSString (HMAC)
- (NSString *)HMACSHA1WithKey:(NSString *)key
{
const char *cKey = [key cStringUsingEncoding:NSUTF8StringEncoding];
const char *cData = [self cStringUsingEncoding:NSUTF8StringEncoding];
unsigned char cHMAC[CC_SHA1_DIGEST_LENGTH];
CCHmac(kCCHmacAlgSHA1, cKey, strlen(cKey), cData, strlen(cData), cHMAC);
NSData *HMAC = [[NSData alloc] initWithBytes:cHMAC length:sizeof(cHMAC)];
return [[NSString alloc] initWithData:HMAC encoding:NSUTF8StringEncoding];
}
@end
I am using this category from RubyMotion like so:
key = "ZjiUOHkl5tllz2PwaoZYrDRMkg9b43k5CcIOUjSE&"
string = "POST&https%3A%2F%2Fapi.twitter.com%2Foauth%2Frequest_token&oauth_consumer_key=XXX&oauth_nonce=OWhJeFpZbzRoVU4xck1RTENyN0w4T1J0czNIa01rSVA&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1389974660&oauth_version=1.0"
string.HMACSHA1WithKey(key) # => nil
However, the HMACSHA1WithKey:
method returns nil
all the time...
What am I doing wrong please?
The result of the SHA-1 algorithm (which is stored in HMAC
) is a sequence of
bytes, but not a valid UTF-8 sequence. Therefore
[[NSString alloc] initWithData:HMAC encoding:NSUTF8StringEncoding]
fails and returns nil
.
What you probably want is to convert the NSData *HMAC
to a NSString
containing the hexadecimal representation of the data.
There are many solutions available for that, for example How to convert an NSData into an NSString Hex string?.