MD5加密,Base64加密/解密,AES加密/解密

时间:2021-12-01 05:01:01

1.从github上下载GTMBase64-master和AESCrypt-ObjC-master导入工程,如下图所示。

MD5加密,Base64加密/解密,AES加密/解密

2.使用前的配置及注意事项:

(1) 在build phases中的GTMBase64.m需要设置 -fno-objc-arc

(2) 在#import "NSString+Base64.m”文件中导入   #import <Foundation/Foundation.h>

(3)在#import "GTMBase64.m”文件中添加          #import <CommonCrypto/CommonCrypto.h>

3. CusMD5.h 和 CusMD5.m 文件

#import <Foundation/Foundation.h>

@interface CusMD5 : NSObject

+ (NSString *)md5String:(NSString *)str;

@end

#import "CusMD5.h"
#import <CommonCrypto/CommonDigest.h> @implementation CusMD5 + (NSString *)md5String:(NSString *)str {
const char *original_str = [str UTF8String];
unsigned char result[CC_MD5_DIGEST_LENGTH];
CC_MD5(original_str, strlen(original_str), result);
NSMutableString *hash = [NSMutableString string];
for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
[hash appendFormat:@"%02X", result[i]];
return [hash lowercaseString]; } @end

   ---> MD5只能称为一种不可逆的加密算法,只能用作一些检验过程,不能恢复其原文。

4. 基本使用

#import "ViewController.h"
#import "CusMD5.h"
#import "GTMBase64.h"
#import "AESCrypt.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad {
[super viewDidLoad]; //要加密的字符串
NSString *strForEn = @"需要加密字符串"; //md5加密
NSString *strEnRes = [CusMD5 md5String:strForEn];
NSLog(@"md5 加密: %@",strEnRes); //base64加密
NSData *dataEn = [strForEn dataUsingEncoding:NSUTF8StringEncoding];
NSData *dataEnRes = [GTMBase64 encodeData:dataEn];
//把加密结果转成string
NSString *base64EnRes = [[NSString alloc] initWithData:dataEnRes encoding:NSUTF8StringEncoding];
NSLog(@"base64加密: %@",base64EnRes); //base64解密
NSData *resDeBase64 = [GTMBase64 decodeData:dataEnRes];
NSString *strDeBase64 = [[NSString alloc] initWithData:resDeBase64 encoding:NSUTF8StringEncoding];
NSLog(@"base64解密: %@",strDeBase64); //aes 加密
NSString *strAESEnRes = [AESCrypt encrypt:strForEn password:@"secret"];
NSLog(@"aes 加密: %@",strAESEnRes); //aes 解密
NSString *strAESDeRes = [AESCrypt decrypt:strAESEnRes password:@"secret"];
NSLog(@"aes 解密: %@",strAESDeRes);
} - (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
} @end