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?
Remarks. HMACSHA1 is a type of keyed hash algorithm that is constructed from the SHA1 hash function and used as an HMAC, or hash-based message authentication code.
HMAC stands for Keyed-Hashing for Message Authentication. It's a message authentication code obtained by running a cryptographic hash function (like MD5, SHA1, and SHA256) over the data (to be authenticated) and a shared secret key. HMAC is specified in RFC 2104. HMACs are almost similar to digital signatures.
Description. The remote SSH server is configured to enable SHA-1 HMAC algorithms. Although NIST has formally deprecated use of SHA-1 for digital signatures, SHA-1 is still considered secure for HMAC as the security of HMAC does not rely on the underlying hash function being resistant to collisions.
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=
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With