Objective-C sample code for HMAC-SHA1 [closed]

I need to generate HMAC-SHA1 in Objective C. But i didnt find anything that works. I tried with CommonCrypto, using CCHMAC, but didnt works. I need to generate a hmac and after generate HOTP number.

Somebody have any example code in Objective C or C?


Here's how you generate an HMAC using SHA-256:

NSString *key;
NSString *data;

const char *cKey  = [key cStringUsingEncoding:NSASCIIStringEncoding];
const char *cData = [data cStringUsingEncoding:NSASCIIStringEncoding];

unsigned char cHMAC[CC_SHA256_DIGEST_LENGTH];

CCHmac(kCCHmacAlgSHA256, cKey, strlen(cKey), cData, strlen(cData), cHMAC);

NSData *HMAC = [[NSData alloc] initWithBytes:cHMAC
                                      length:sizeof(cHMAC)];

NSString *hash = [HMAC base64Encoding];

I'm not aware of an HOTP library, but the algorithm was quite simple, if I recall correctly.


here is how you can generate HMAC-SHA1 base64.

You need to add Base64.h and Base64.m to your project. You can get it from here.

If you use ARC, it will show some errors in Base64.m. Find the lines who are similar like this

return [[[self alloc] initWithBase64String:base64String] autorelease];

what you need is to delete the autorelease section. The final result should look like:

return [[self alloc] initWithBase64String:base64String];

Now in your general project import "Base64.h" and the following code

#import "Base64.h"
#include <CommonCrypto/CommonDigest.h>
#include <CommonCrypto/CommonHMAC.h>

- (NSString *)hmacsha1:(NSString *)data secret:(NSString *)key {

    const char *cKey  = [key cStringUsingEncoding:NSASCIIStringEncoding];
    const char *cData = [data cStringUsingEncoding:NSASCIIStringEncoding];

    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)];

    NSString *hash = [HMAC base64String];

    return hash;
}

With

NSLog(@"Hash: %@", hash);  

you will get something similar to this:

ghVEjPvxwLN1lBi0Jh46VpIchOc=