Last active
March 22, 2017 20:12
-
-
Save DonMag/128d0122465ec63ea7d40a744d62dbc5 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #import <Foundation/Foundation.h> | |
| #import <CommonCrypto/CommonHMAC.h> | |
| #import "ViewController.h" | |
| @implementation ViewController | |
| - (NSData *)dataFromHexString:(NSString *)sHex { | |
| const char *chars = [sHex UTF8String]; | |
| int i = 0; | |
| NSUInteger len = sHex.length; | |
| NSMutableData *data = [NSMutableData dataWithCapacity:len / 2]; | |
| char byteChars[3] = {'\0','\0','\0'}; | |
| unsigned long wholeByte; | |
| while (i < len) { | |
| byteChars[0] = chars[i++]; | |
| byteChars[1] = chars[i++]; | |
| wholeByte = strtoul(byteChars, NULL, 16); | |
| [data appendBytes:&wholeByte length:1]; | |
| } | |
| return data; | |
| } | |
| - (NSData *)hmacForHexKey:(NSString *)hexkey andStringData:(NSString *)data | |
| { | |
| NSData *keyData = [self dataFromHexString:hexkey]; | |
| const char *cKey = [keyData bytes]; | |
| const char *cData = [data cStringUsingEncoding:NSUTF8StringEncoding]; | |
| unsigned char cHMAC[CC_SHA256_DIGEST_LENGTH]; | |
| CCHmac(kCCHmacAlgSHA256, cKey, keyData.length, cData, strlen(cData), cHMAC); | |
| return [[NSData alloc] initWithBytes:cHMAC length:sizeof(cHMAC)]; | |
| } | |
| - (NSData *)hmacForKey:(NSString *)key andStringData:(NSString *)data | |
| { | |
| const char *cKey = [key cStringUsingEncoding:NSUTF8StringEncoding]; | |
| const char *cData = [data cStringUsingEncoding:NSUTF8StringEncoding]; | |
| unsigned char cHMAC[CC_SHA256_DIGEST_LENGTH]; | |
| CCHmac(kCCHmacAlgSHA256, cKey, strlen(cKey), cData, strlen(cData), cHMAC); | |
| return [[NSData alloc] initWithBytes:cHMAC length:sizeof(cHMAC)]; | |
| } | |
| - (void)viewDidLoad { | |
| [super viewDidLoad]; | |
| // Do any additional setup after loading the view, typically from a nib. | |
| NSString *key = @"This is my random key."; | |
| NSString *hexKey = @"54686973206973206d792072616e646f6d206b65792e"; | |
| NSString *data = @"This is a data string."; | |
| NSData *hmac1 = [self hmacForKey:key andStringData:data]; | |
| NSLog(@"hmacForKey : %@", hmac1); | |
| NSData *hmac2 = [self hmacForHexKey:hexKey andStringData:data]; | |
| NSLog(@"hmacForHexKey: %@", hmac2); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment