iPhone SHA-1编码Rails的不同结果?

时间:2011-07-18 15:18:00

标签: iphone objective-c ruby-on-rails encoding

Ruby代码:

  a = OpenSSL::HMAC.digest('sha1', 'secret', 'example')

然后:

 Base64.encode64(a).chomp

产量

 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];
}

并且

[XICrypto hmac:@"example" withKey:@"secret"];
NSLog(@"HMACData: %@",[HMACData description]);
NSString *HMACEncodedString = [HMACData base64Encoding];

(其中base64Encoding方法来自Alex Reynold对Cocoa Base 64 Implementation for REST Auth的回答)

结果产量

Qm+ManmzmtfhpOzFdf8UHW43L5o=

所以这些方法没有执行相同的操作,为什么?

编辑:摘要和密钥在Rails调用中倒退。修复了这个问题,但结果仍然与iPhone的调用不同。

1 个答案:

答案 0 :(得分:3)

是的,我在看到自己的那个部分后看到了你的评论:),你的rails调用是向后的,你的下一个问题是编码。当使用字符串编码时,如果您想要正确的字节长度,请使用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];
}

我记录了数据的内容并获得68ca7a67 0d7e8475 4c9b0597 a05a7f01 a8a9736d,如果您将其粘贴到this translator的十六进制字段中,您将在base64字段中获得aMp6Zw1+hHVMmwWXoFp/Aaipc20=