Xcode的IOS HMAC SHA哈希256(xcode ios HMAC SHA 256 has

2019-08-08 05:10发布

所以我想弄清楚如何做一个hmacshad256散在iOS因为这是我为WCF服务API我发的哈希值。 我一直在试图寻找关于它的一些信息,但通常会只落得得到一个SHA-256散列。

这是我唯一的参考:

需要生成目标C HMAC SHA256散列作为Java中

而且我不知道这是应该做的唯一途径(导入一个java类HMAC)

任何帮助表示赞赏。

谢谢!

Answer 1:

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


Answer 2:

下面是我提交,我放在一起,从对此事的其他答案的解决方案:

这是很容易通过改变CC_SHA256_DIGEST_LENGTH和kCCHmacAlgSHA256适用于其他哈希类型。

如果你有兴趣这样做,检查出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版测试



Answer 3:

 + (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; } 



文章来源: xcode ios HMAC SHA 256 hashing