1,新建NSString的分類,記得添加加密所需的頭文件#import <CommonCrypto/CommonDigest.h> , NSString+MD5.h:
#import <Foundation/Foundation.h> #import <CommonCrypto/CommonDigest.h> @interface NSString (MD5) + (NSString *)md5To32bit:(NSString *)str; @end
2,編寫加密方法:
#import "NSString+MD5.h" @implementation NSString (MD5) + (NSString *)md5To32bit:(NSString *)str { const char *cStr = [str UTF8String]; unsigned char digest[CC_MD5_DIGEST_LENGTH]; CC_MD5( cStr, strlen(cStr),digest ); NSMutableString *result = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2]; for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++) [result appendFormat:@"%02x", digest[i]]; return result; }
3,在需要加密的字串符當前控制器中導入頭文件,並引用該方法:
#import "ViewController.h" #import "NSString+MD5.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; NSString *name = @"Kuture"; //加密字符串 NSString *encypt = [NSString md5To32bit:name]; NSLog(@"\n name: %@\n encypt: %@",name,encypt); } @end
運行結果為:
以上就是本文的全部內容了,希望大家能夠喜歡。