加密函数
注意要包含
#import <CommonCrypto/CommonDigest.h>
//哈希加密
+ (NSString *)Base_HmacSha1:(NSString *)key data:(NSString *)data;
+ (NSString *)sha1:(NSString *)inputString;
//md5加密方法
+ (NSString *)md5:(NSString *)input;
具体代码
1.哈希加密
//hmac加密
+ (NSString *)Base_HmacSha1:(NSString *)key data:(NSString *)data{
const char *cKey = [key cStringUsingEncoding:NSASCIIStringEncoding];
const char *cData = [data cStringUsingEncoding:NSASCIIStringEncoding];
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;
}
//哈希
+ (NSString *)sha1:(NSString *)inputString{
NSData *data = [inputString dataUsingEncoding:NSUTF8StringEncoding];
uint8_t digest[CC_SHA1_DIGEST_LENGTH];
CC_SHA1(data.bytes,(unsigned int)data.length,digest);
NSMutableString *outputString = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH];
for (int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++) {
[outputString appendFormat:@"%02x",digest[i]];
}
return [outputString lowercaseString];
}
2.md5
+ (NSString *)md5:(NSString *)input{
const char *cStr = [input UTF8String];
unsigned char digest[CC_MD5_DIGEST_LENGTH];
CC_MD5(cStr,(CC_LONG)strlen(cStr),digest);
NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
[output appendFormat:@"%02x", digest[i]];//注意这里的x绝对不能大写成X。。。
return output;
}