views:

5117

answers:

3

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?

+11  A: 

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.

Can Berk Güder
base64Encoding have in object c??I tried compile it, but i get an error this line. [HMAC base64Encoding];
Helena
oohh...so thank u very muchhhh!!!
Helena
@Helena: oops, base64Encoding is from a custom NSData protocol. =) I'm glad the rest of the code worked, though.
Can Berk Güder
rsrsrs... si si... it worked!!!argh!!!rsrsrs...u speak spanish...hm
Helena
? nope, I don't speak Spanish, sorry.
Can Berk Güder
Ah...Okay! =) no problem
Helena
Thanks a ton.. :)
lostInTransit
A: 

Have you seen Jens Alfke's new MyCrypto classes?

He has some sample code on his blog.

Ford
soo thankk uu very much ford
Helena
A: 

See http://oathtoken.googlecode.com/ for an iPhone app that does it.

Archie