Last active
November 23, 2018 01:47
-
-
Save muhlenXi/9bed638f48509ae583d649eae6b959ac to your computer and use it in GitHub Desktop.
对字符串进行MD5或SHA1 加密
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 需要 #import <CommonCrypto/CommonDigest.h> | |
// 对字符串进行MD5加密 | |
+ (NSString *)MD5WithString:(NSString *)string | |
{ | |
const char *cStr = [string UTF8String]; | |
unsigned char digest[CC_MD5_DIGEST_LENGTH]; | |
CC_MD5( cStr, (uint32_t)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]]; | |
return output; | |
} | |
// 对字符串进行SHA1加密 | |
+ (NSString *)SHA1WithString:(NSString *)string | |
{ | |
const char *cstr = [string cStringUsingEncoding:NSUTF8StringEncoding]; | |
NSData *data = [NSData dataWithBytes:cstr length:string.length]; | |
//使用对应的CC_SHA1,CC_SHA256,CC_SHA384,CC_SHA512的长度分别是20,32,48,64 | |
uint8_t digest[CC_SHA1_DIGEST_LENGTH]; | |
//使用对应的CC_SHA256,CC_SHA384,CC_SHA512 | |
CC_SHA1(data.bytes, (uint32_t)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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment