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

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


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=

 


This is the complete solution which works without any extra libraries or hacks:

+(NSString *)hmac:(NSString *)plainText withKey:(NSString *)key{    const char *cKey  = [key cStringUsingEncoding:NSASCIIStringEncoding];    const char *cData = [plainText cStringUsingEncoding:NSASCIIStringEncoding];    unsigned char cHMAC[CC_SHA256_DIGEST_LENGTH];    CCHmac(kCCHmacAlgSHA256, cKey, strlen(cKey), cData, strlen(cData), cHMAC);    NSData *HMACData = [[NSData alloc] initWithBytes:cHMAC length:sizeof(cHMAC)];    const unsigned char *buffer = (const unsigned char *)[HMACData bytes];    NSString *HMAC = [NSMutableString stringWithCapacity:HMACData.length * 2];    for (int i = 0; i < HMACData.length; ++i)        HMAC = [HMAC stringByAppendingFormat:@"%02lx", (unsigned long)buffer[i]];    return HMAC;}

You don't have to include any third-party base64 library as it is already encoded.