开发者

iPhone SHA-1 encoding different results from Rails?

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(kC开发者_如何学GoCHmacAlgSHA1, 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:.

+ (NSData *)hmac:(NSString *)input withKey:(NSString *)key {
    NSStringEncoding encoding = NSASCIIStringEncoding;
    const char *cstrInput = [input cStringUsingEncoding:encoding];
    NSUInteger inputLength = [input lengthOfBytesUsingEncoding:encoding];
    const char *cstrKey = [key cStringUsingEncoding:encoding];
    NSUInteger keyLength = [key lengthOfBytesUsingEncoding:encoding];

    unsigned char chmac[CC_SHA1_DIGEST_LENGTH];
    CCHmac(kCCHmacAlgSHA1, cstrKey, keyLength, cstrInput, inputLength, &chmac);

    return [[[NSData alloc] initWithBytes:chmac length:sizeof(chmac)] autorelease];
}

I logged the contents of the data and get 68ca7a67 0d7e8475 4c9b0597 a05a7f01 a8a9736d and if you paste that into the hex field of this translator you will get aMp6Zw1+hHVMmwWXoFp/Aaipc20= in the base64 field.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜