xcode ios HMAC SHA 256哈希
所以我想弄清楚如何在ios上做一个hmacshad256散列,因为这是我为我做的wcf服务api所做的散列。 我一直在试图寻找一些关于它的信息,但通常只会得到一个SHA-256散列。
这是我唯一的参考:
需要像在Java中一样在Objective C中生成HMAC SHA256哈希
我不确定这是否是唯一的方法(导入一个java hmac类)
任何帮助表示赞赏。
谢谢!
NSString * parameters = @"string to hash" NSString *salt = @"saltStringHere"; NSData *saltData = [salt dataUsingEncoding:NSUTF8StringEncoding]; NSData *paramData = [parameters dataUsingEncoding:NSUTF8StringEncoding]; NSMutableData* hash = [NSMutableData dataWithLength:CC_SHA256_DIGEST_LENGTH ]; CCHmac(kCCHmacAlgSHA256, saltData.bytes, saltData.length, paramData.bytes, paramData.length, hash.mutableBytes); NSString *base64Hash = [hash base64Encoding];
并且
#import <CommonCrypto/CommonHMAC.h>
由于base64Encoding
从iOS 7.0 被弃用 ,最后一行应该是:
NSString *base64Hash = [hash base64EncodedStringWithOptions:0];
这是我提交的解决scheme,我把这个问题的其他答案放在一起:
通过改变CC_SHA256_DIGEST_LENGTH和kCCHmacAlgSHA256,这很容易适应其他散列types。
如果您对此感兴趣,请查看CommonCrypto库中的CommonDigest.h文件。
#import <Foundation/Foundation.h> #import <CommonCrypto/CommonCrypto.h> + (NSString *)hmac:(NSString *)plaintext withKey:(NSString *)key { const char *cKey = [key cStringUsingEncoding:NSASCIIStringEncoding]; const char *cData = [plaintext cStringUsingEncoding:NSASCIIStringEncoding]; unsigned char cHMAC[CC_SHA256_DIGEST_LENGTH]; CCHmac(kCCHmacAlgSHA256, cKey, strlen(cKey), cData, strlen(cData), cHMAC); NSData *HMACData = [NSData dataWithBytes:cHMAC length:sizeof(cHMAC)]; const unsigned char *buffer = (const unsigned char *)[HMACData bytes]; NSMutableString *HMAC = [NSMutableString stringWithCapacity:HMACData.length * 2]; for (int i = 0; i < HMACData.length; ++i){ [HMAC appendFormat:@"%02x", buffer[i]]; } return HMAC; }
这已经在iOS 8.x和iOS 7.x上进行了testing
+ (NSString *)hmacSHA256EncryptString{ NSString * parameterSecret = @"input secret key"; NSString *plainString = @"input encrypt content string"; const char *secretKey = [parameterSecret cStringUsingEncoding:NSUTF8StringEncoding]; const char *plainData = [plainString cStringUsingEncoding:NSUTF8StringEncoding]; unsigned char cHMAC[CC_SHA256_DIGEST_LENGTH]; CCHmac(kCCHmacAlgSHA256, secretKey, strlen(secretKey), plainData, strlen(plainData), cHMAC); NSData *HMACData = [NSData dataWithBytes:cHMAC length:sizeof(cHMAC)]; const unsigned char *bufferChar = (const unsigned char *)[HMACData bytes]; NSMutableString *hmacString = [NSMutableString stringWithCapacity:HMACData.length * 2]; for (int i = 0; i < HMACData.length; ++i){ [hmacString appendFormat:@"%02x", bufferChar[i]]; } return hmacString; }