iOS中使用MD5加密字符串

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

运行结果为:

以上是 iOS中使用MD5加密字符串 的全部内容, 来源链接: utcz.com/z/337445.html

回到顶部