------------------.h文件--------------------
#import<Foundation/Foundation.h>
@interface NSString (SHA256)
- (NSString *)SHA256;
@end
-----------------------------------------------
#import "NSString+SHA256.h"
#import
@implementation NSString (SHA256)
-------------------------.m文件---------------------------------
#import "NSString+SHA256.h"
#import<CommonCrypto/CommonDigest.h>
- (NSString *)SHA256
{
const char *s = [self cStringUsingEncoding:NSASCIIStringEncoding];
NSData *keyData = [NSData dataWithBytes:s length:strlen(s)];
uint8_t digest[CC_SHA256_DIGEST_LENGTH] = {0};
CC_SHA256(keyData.bytes, (CC_LONG)keyData.length, digest);
NSData *out = [NSData dataWithBytes:digest length:CC_SHA256_DIGEST_LENGTH];
? ? const unsigned char *buffer = (const unsigned char *)[out bytes];
? ? NSMutableString *HMAC = [NSMutableString stringWithCapacity:out.length * 2];
? ? for(inti =0; i
? ? [HMACappendFormat:@"%02x", buffer[i]];
? ? }
NSString* haSha = [HMAC uppercaseString];//如果后臺將數(shù)據(jù)轉(zhuǎn)化為大寫洞难,此處也應(yīng)該轉(zhuǎn)為大寫
returnhaSha;
}
@end
-------------------------------------------------------------
如果是后臺對key加密的話
#import <CommonCrypto/CommonDigest.h>
#import <CommonCrypto/CommonHMAC.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;
}