Skip to content

Instantly share code, notes, and snippets.

@rsattar
Created February 20, 2013 19:30
Show Gist options
  • Save rsattar/4998533 to your computer and use it in GitHub Desktop.
Save rsattar/4998533 to your computer and use it in GitHub Desktop.
Generating an X-AvoSig string for signing API requests for Avocado
// Requires Security.framework on Cocoa and Cocoa-Touch
#import <CommonCrypto/CommonDigest.h>
- (NSString *)avoSigFromUserEmailHash:(NSString *)userEmailHash developerKey:(NSString *)developerKey developerId:(NSString *)developerId
{
NSString *combo = [userEmailHash stringByAppendingString:developerKey];
unsigned char result[CC_SHA256_DIGEST_LENGTH];
const char *combined = [combo UTF8String];
CC_SHA256(combined, [combo lengthOfBytesUsingEncoding:NSUTF8StringEncoding], result);
NSData *resultData = [NSData dataWithBytes:result length:CC_SHA256_DIGEST_LENGTH];
NSString *hash = [self hexadecimalStringFromNSData:resultData];
return [NSString stringWithFormat:@"%@:%@", developerId, hash];
}
// From: http://stackoverflow.com/questions/1305225/best-way-to-serialize-a-nsdata-into-an-hexadeximal-string
- (NSString *)hexadecimalStringFromNSData:(NSData *)data {
/* Returns hexadecimal string of NSData. Empty string if data is empty. */
const unsigned char *dataBuffer = (const unsigned char *)[data bytes];
if (!dataBuffer) {
return [NSString string];
}
NSUInteger dataLength = [data length];
NSMutableString *hexString = [NSMutableString stringWithCapacity:(dataLength * 2)];
for (int i = 0; i < dataLength; ++i) {
[hexString appendString:[NSString stringWithFormat:@"%02lx", (unsigned long)dataBuffer[i]]];
}
return [NSString stringWithString:hexString];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment