Ruby code:
a = OpenSSL::HMAC.digest('sha1', 'secret', 'example')
and then:
Base64.encode64(a).chomp
yields
aMp6Zw1+hHVMmwWXoFp/Aaipc20=
iPhone:
+ (NSData *)hmac:(NSString *)input withKey:(NSString *)key {
const char *cstrInput = [input cStringUsingEncoding:NSASCIIStringEncoding];
const char *cstrKey = [key cStringUsingEncoding:NSASCIIStringEncoding];
NSData *data = [NSData dataWithBytes:cstrInput length:input.length];
unsigned char chmac[CC_SHA1_DIGEST_LENGTH];
CCHmac(kCCHmacAlgSHA1, cstrKey, strlen(cstrKey), data, [data length], &chmac);
NSData *hmacData = [[NSData alloc] initWithBytes:chmac length:sizeof(chmac)];
return [hmacData autorelease];
}
And
[XICrypto hmac:@"example" withKey:@"secret"];
NSLog(@"HMACData: %@",[HMACData description]);
NSString *HMACEncodedString = [HMACData base64Encoding];
(Where base64Encoding method is from Alex Reynold’s answer on Cocoa Base 64 Implementation for REST Auth)
Results yield
Qm+ManmzmtfhpOzFdf8UHW43L5o=
So these methods are not performing the same operations, why?
EDIT: digest and key were backwards in the Rails call. Fixed that, yet the result is still different from the iPhone’s call.
Yes I see your comment after I figured out that part on my own :), your rails call is backwards, your next issue is encoding. When ever you want the correct length of bytes when using string encoding use
lengthOfBytesUsingEncoding:.I logged the contents of the data and get
68ca7a67 0d7e8475 4c9b0597 a05a7f01 a8a9736dand if you paste that into the hex field of this translator you will getaMp6Zw1+hHVMmwWXoFp/Aaipc20=in the base64 field.