做了一个项目,直接导入#import <CommonCrypto/CommonDigest.h>,发现系统自带的方法不能用,所以新建了一个, 新建一个NSString+MD5类,在.h文件中
@import Foundation;
#ifdef NS_ASSUME_NONNULL_BEGIN
NS_ASSUME_NONNULL_BEGIN
#endif
@interface NSString (MD5)
- (NSString *)MD5Digest;
@end
#ifdef NS_ASSUME_NONNULL_END
NS_ASSUME_NONNULL_END
#endif
在.m文件中
#import <CommonCrypto/CommonDigest.h>
#import "NSString+MD5.h"
@implementation NSString (MD5)
- (NSString *)MD5Digest
{
const char* input = [self UTF8String];
unsigned char result[CC_MD5_DIGEST_LENGTH];
CC_MD5(input, (CC_LONG)strlen(input), result);
NSMutableString *digest = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
for (NSInteger i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
[digest appendFormat:@"%02x", result[i]];
}
return digest;
}
@end
方法使用:
NSString * secret = @"a1b2c3";
NSString *result = [secret MD5Digest];
result = result.uppercaseString;