我正在尝试使用CCHmac()用HMAC-SHA1加密字符串。我创建了一个NSString类别
为了这:

NSString + HMAC.h

#import <Foundation/Foundation.h>
#import <CommonCrypto/CommonDigest.h>
#import <CommonCrypto/CommonHMAC.h>

@interface NSString (HMAC)

- (NSString *)HMACSHA1WithKey:(NSString *)key;

@end


NSString + HMAC.m

#import "NSString+HMAC.h"

@implementation NSString (HMAC)

- (NSString *)HMACSHA1WithKey:(NSString *)key
{
    const char *cKey  = [key cStringUsingEncoding:NSUTF8StringEncoding];
    const char *cData = [self cStringUsingEncoding:NSUTF8StringEncoding];

    unsigned char cHMAC[CC_SHA1_DIGEST_LENGTH];

    CCHmac(kCCHmacAlgSHA1, cKey, strlen(cKey), cData, strlen(cData), cHMAC);

    NSData *HMAC = [[NSData alloc] initWithBytes:cHMAC length:sizeof(cHMAC)];

    return [[NSString alloc] initWithData:HMAC encoding:NSUTF8StringEncoding];
}

@end


我正在像这样从RubyMotion使用此类别:

key = "ZjiUOHkl5tllz2PwaoZYrDRMkg9b43k5CcIOUjSE&"
string = "POST&https%3A%2F%2Fapi.twitter.com%2Foauth%2Frequest_token&oauth_consumer_key=XXX&oauth_nonce=OWhJeFpZbzRoVU4xck1RTENyN0w4T1J0czNIa01rSVA&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1389974660&oauth_version=1.0"
string.HMACSHA1WithKey(key) # => nil


但是,HMACSHA1WithKey:方法始终会返回nil

请问我做错了什么?

最佳答案

SHA-1算法的结果(存储在HMAC中)是一个序列
个字节,但不是有效的UTF-8序列。因此

[[NSString alloc] initWithData:HMAC encoding:NSUTF8StringEncoding]


失败并返回nil

您可能想要的是将NSData *HMAC转换为包含数据的十六进制表示形式的NSString
有许多解决方案,例如How to convert an NSData into an NSString Hex string?

关于ios - 使用CommonCrypto的NSString类别在RubyMotion中返回nil,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21190537/

10-13 08:44