MD5/SHA1/Hmac_SHA1
1、MD5
#import <CommonCrypto/CommonDigest.h>
+ (NSString *) md5:(NSString *) input { const char *cStr = [input UTF8String]; unsigned char digest[CC_MD5_DIGEST_LENGTH]; CC_MD5( cStr, (unsigned int)strlen(cStr), digest ); // This is the md5 call NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2]; for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++) [output appendFormat:@"%02x", digest[i]]; return output; }
2、SHA1
+ (NSString *) sha1:(NSString *)input{ NSData *data = [input dataUsingEncoding:NSUTF8StringEncoding]; uint8_t digest[CC_SHA1_DIGEST_LENGTH]; CC_SHA1(data.bytes, (unsigned int)data.length, digest); NSMutableString *output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2]; for(int i=0; i<CC_SHA1_DIGEST_LENGTH; i++) { [output appendFormat:@"%02x", digest[i]]; } return output; }
3、HmacSHA1
//额外添加了base64转码
+(NSString *)Base_HmacSha1:(NSString *)key data:(NSString *)data{
const char *cKey = [key cStringUsingEncoding:NSASCIIStringEncoding];
const char *cData = [data cStringUsingEncoding:NSASCIIStringEncoding];
//Sha256:
// unsigned char cHMAC[CC_SHA256_DIGEST_LENGTH];
//CCHmac(kCCHmacAlgSHA256, cKey, strlen(cKey), cData, strlen(cData), cHMAC);
//sha1
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)];
//将加密结果进行一次BASE64编码。
NSString *hash = [HMAC base64EncodedStringWithOptions:0];
return hash;
}