Skip to content

Instantly share code, notes, and snippets.

@aldo-jlaurenstin
Created October 7, 2015 20:30
Show Gist options
  • Save aldo-jlaurenstin/96db6f5c0e651732c842 to your computer and use it in GitHub Desktop.
Save aldo-jlaurenstin/96db6f5c0e651732c842 to your computer and use it in GitHub Desktop.
Objective-C sample code for HMAC-SHA1
//
// ALCommonHMAC.h
//
// As discussed in http://stackoverflow.com/questions/756492/objective-c-sample-code-for-hmac-sha1
//
// Created by James Laurenstin on 2015-15-09.
// Copyright (c) 2015 Aldo Group Inc. All rights reserved.
//
//
#import <CommonCrypto/CommonHMAC.h>
#import <Foundation/Foundation.h>
@interface ALCommonHMAC : NSObject
+ (NSString*)hmacSHA256:(NSString*)data withKey:(NSString *)key;
+ (NSString*)base64forData:(NSData*)theData;
@end
//
// ALCommonHMAC.m
// mFind
//
// As discussed in http://stackoverflow.com/questions/756492/objective-c-sample-code-for-hmac-sha1
//
// Created by James Laurenstin on 2015-15-09.
// Copyright (c) 2015 Aldo Group Inc. All rights reserved.
//
#import "ALCommonHMAC.h"
@implementation ALCommonHMAC
+ (NSString*)hmacSHA256:(NSString*)data withKey:(NSString *)key {
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 *hash = [[NSData alloc] initWithBytes:cHMAC length:sizeof(cHMAC)];
return [ALCommonHMAC base64forData:hash];
}
+ (NSString*)base64forData:(NSData*)theData {
const uint8_t* input = (const uint8_t*)[theData bytes];
NSInteger length = [theData length];
static char table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
NSMutableData* data = [NSMutableData dataWithLength:((length + 2) / 3) * 4];
uint8_t* output = (uint8_t*)data.mutableBytes;
NSInteger i;
for (i=0; i < length; i += 3) {
NSInteger value = 0;
NSInteger j;
for (j = i; j < (i + 3); j++) {
value <<= 8;
if (j < length) { value |= (0xFF & input[j]); } } NSInteger theIndex = (i / 3) * 4; output[theIndex + 0] = table[(value >> 18) & 0x3F];
output[theIndex + 1] = table[(value >> 12) & 0x3F];
output[theIndex + 2] = (i + 1) < length ? table[(value >> 6) & 0x3F] : '=';
output[theIndex + 3] = (i + 2) < length ? table[(value >> 0) & 0x3F] : '=';
}
return [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
}
@end
@aldo-jlaurenstin
Copy link
Author

As discussed here: http://stackoverflow.com/questions/756492/objective-c-sample-code-for-hmac-sha1

This helps generate HMAC-SHA1 in Objective C (can be easily added to your swift project as well).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment