本文主要是介绍IOS 纯DES加密 与 使用base64加密,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
DES是一种分组数据加密技术(先将数据分成固定长度的小数据块,之后进行加密),速度较快,适用于大量数据加密
3DES是一种基于DES的加密算法,使用3个不同密匙对同一个分组数据块进行3次加密,如此以使得密文强度更高。
相较于DES和3DES算法而言,AES算法有着更高的速度和资源使用效率,安全级别也较之更高了,被称为下一代加密标准。
使用前先下载GTMBase64 与 GTMDefines 文件;
用DES实现加密和解密的过程:(注释是我自己理解添加。不对的地方望指出)
.h文件中:
+ (NSString *)encryptWithText:(NSString *)sText;//加密
+ (NSString *)decryptWithText:(NSString *)sText;//解密
.m文件中 (导包: #import "GTMBase64.h"(下面说) #import <CommonCrypto/CommonCryptor.h> )
+ (NSString *)encryptWithText:(NSString *)sText
{ //kCCEncrypt 加密 return [self encrypt:sText encryptOrDecrypt:kCCEncrypt key:@"des"];
} + (NSString *)decryptWithText:(NSString *)sText
{ //kCCDecrypt 解密 return [self encrypt:sText encryptOrDecrypt:kCCDecrypt key:@"des"];
} + (NSString *)encrypt:(NSString *)sText encryptOrDecrypt:(CCOperation)encryptOperation key:(NSString *)key
{ const void *dataIn; size_t dataInLength; if (encryptOperation == kCCDecrypt)//传递过来的是decrypt 解码 { //解码 base64 NSData *decryptData = [GTMBase64 decodeData:[sText dataUsingEncoding:NSUTF8StringEncoding]];//转成utf-8并decode dataInLength = [decryptData length]; dataIn = [decryptData bytes]; } else //encrypt { NSData* encryptData = [sText dataUsingEncoding:NSUTF8StringEncoding]; dataInLength = [encryptData length]; dataIn = (const void *)[encryptData bytes]; } /* DES加密 :用CCCrypt函数加密一下,然后用base64编码下,传过去 DES解密 :把收到的数据根据base64,decode一下,然后再用CCCrypt函数解密,得到原本的数据 */ CCCryptorStatus ccStatus; uint8_t *dataOut = NULL; //可以理解位type/typedef 的缩写(有效的维护了代码,比如:一个人用int,一个人用long。最好用typedef来定义) size_t dataOutAvailable = 0; //size_t 是操作符sizeof返回的结果类型 size_t dataOutMoved = 0; dataOutAvailable = (dataInLength + kCCBlockSizeDES) & ~(kCCBlockSizeDES - 1); dataOut = malloc( dataOutAvailable * sizeof(uint8_t)); memset((void *)dataOut, 0x0, dataOutAvailable);//将已开辟内存空间buffer的首 1 个字节的值设为值 0 NSString *initIv = @"12345678"; const void *vkey = (const void *) [key UTF8String]; const void *iv = (const void *) [initIv UTF8String]; //CCCrypt函数 加密/解密 ccStatus = CCCrypt(encryptOperation,// 加密/解密 kCCAlgorithmDES,// 加密根据哪个标准(des,3des,aes。。。。) kCCOptionPKCS7Padding,// 选项分组密码算法(des:对每块分组加一次密 3DES:对每块分组加三个不同的密) vkey, //密钥 加密和解密的密钥必须一致 kCCKeySizeDES,// DES 密钥的大小(kCCKeySizeDES=8) iv, // 可选的初始矢量 dataIn, // 数据的存储单元 dataInLength,// 数据的大小 (void *)dataOut,// 用于返回数据 dataOutAvailable, &dataOutMoved); NSString *result = nil; if (encryptOperation == kCCDecrypt)//encryptOperation==1 解码 { //得到解密出来的data数据,改变为utf-8的字符串 result = [[[NSString alloc] initWithData:[NSData dataWithBytes:(const void *)dataOut length:(NSUInteger)dataOutMoved] encoding:NSUTF8StringEncoding] autorelease]; } else //encryptOperation==0 (加密过程中,把加好密的数据转成base64的) { //编码 base64 NSData *data = [NSData dataWithBytes:(const void *)dataOut length:(NSUInteger)dataOutMoved]; result = [GTMBase64 stringByEncodingData:data]; } return result;
测试:
NSString *encrypt = [ViewController encryptWithText:@"中华人民共和国万岁!!"]; NSLog(@"enctry = %@",encrypt); NSString *decrypt = [ViewController decryptWithText:encrypt]; NSLog(@"decrypt = %@",decrypt);
未使用base64加密 纯des加密
// 把一个byte数据转换为字符串
+(NSString *) parseByte2HexString:(Byte *) bytes;
// 把一个byte数组转换为字符串
+(NSString *) parseByteArray2HexString:(Byte[]) bytes;// nsData 转16进制
+ (NSString*)stringWithHexBytes2:(NSData *)sender;/****** 加密 ******/
+(NSString *) encryptUseDES:(NSString *)clearText key:(NSString *)key;
/****** 解密 ******/
+(NSString *) decryptUseDES:(NSString *)plainText key:(NSString *)key;
#import "DES.h"
#import <CommonCrypto/CommonCryptor.h>//static Byte iv[] = {'3','B','1','3','0','8','B','5'};//only Used for Cipher Block Chaining (CBC) mode,This is ignored if ECB mode is used
@implementation DES#pragma mark - DES_Mothed
/******************************************************************************函数描述 : 文本数据进行DES加密******************************************************************************/
+(NSString *) encryptUseDES:(NSString *)clearText key:(NSString *)key
{NSString *ciphertext = nil;NSData *textData = [clearText dataUsingEncoding:NSUTF8StringEncoding];NSUInteger dataLength = [textData length];size_t bufferSize = dataLength + kCCBlockSizeAES128;void * buffer = malloc(bufferSize);size_t numBytesEncrypted = 0;CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmDES,kCCOptionPKCS7Padding | kCCOptionECBMode,[key UTF8String], kCCBlockSizeDES,NULL,[textData bytes] , dataLength,buffer, bufferSize,&numBytesEncrypted);if (cryptStatus == kCCSuccess) {NSLog(@"DES加密成功");NSData *data = [NSData dataWithBytes:buffer length:(NSUInteger)numBytesEncrypted];ciphertext = [self stringWithHexBytes2:data];}else{NSLog(@"DES加密失败");}free(buffer);return ciphertext;
}/******************************************************************************函数描述 : 文本数据进行DES解密******************************************************************************/
+(NSString *) decryptUseDES:(NSString *)plainText key:(NSString *)key
{NSString *cleartext = nil;NSData *textData = [self parseHexToByteArray:plainText];NSUInteger dataLength = [textData length];size_t bufferSize = dataLength + kCCBlockSizeAES128;void *buffer = malloc(bufferSize);size_t numBytesEncrypted = 0;CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, kCCAlgorithmDES,kCCOptionPKCS7Padding | kCCOptionECBMode,[key UTF8String], kCCKeySizeDES,NULL,[textData bytes] , dataLength,buffer, bufferSize,&numBytesEncrypted);if (cryptStatus == kCCSuccess) {NSLog(@"DES解密成功");NSData *data = [NSData dataWithBytes:buffer length:(NSUInteger)numBytesEncrypted];cleartext = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];}else{NSLog(@"DES解密失败");}free(buffer);return cleartext;
}//nsdata转成16进制字符串
+ (NSString*)stringWithHexBytes2:(NSData *)sender {static const char hexdigits[] = "0123456789ABCDEF";const size_t numBytes = [sender length];const unsigned char* bytes = [sender bytes];char *strbuf = (char *)malloc(numBytes * 2 + 1);char *hex = strbuf;NSString *hexBytes = nil;for (int i = 0; i<numBytes; ++i) {const unsigned char c = *bytes++;*hex++ = hexdigits[(c >> 4) & 0xF];*hex++ = hexdigits[(c ) & 0xF];}*hex = 0;hexBytes = [NSString stringWithUTF8String:strbuf];free(strbuf);return hexBytes;
}/*将16进制数据转化成NSData 数组*/
+(NSData*) parseHexToByteArray:(NSString*) hexString
{int j=0;Byte bytes[hexString.length];for(int i=0;i<[hexString length];i++){int int_ch; /// 两位16进制数转化后的10进制数unichar hex_char1 = [hexString characterAtIndex:i]; 两位16进制数中的第一位(高位*16)int int_ch1;if(hex_char1 >= '0' && hex_char1 <='9')int_ch1 = (hex_char1-48)*16; 0 的Ascll - 48else if(hex_char1 >= 'A' && hex_char1 <='F')int_ch1 = (hex_char1-55)*16; A 的Ascll - 65elseint_ch1 = (hex_char1-87)*16; a 的Ascll - 97i++;unichar hex_char2 = [hexString characterAtIndex:i]; ///两位16进制数中的第二位(低位)int int_ch2;if(hex_char2 >= '0' && hex_char2 <='9')int_ch2 = (hex_char2-48); 0 的Ascll - 48else if(hex_char2 >= 'A' && hex_char1 <='F')int_ch2 = hex_char2-55; A 的Ascll - 65elseint_ch2 = hex_char2-87; a 的Ascll - 97int_ch = int_ch1+int_ch2;bytes[j] = int_ch; ///将转化后的数放入Byte数组里j++;}NSData *newData = [[NSData alloc] initWithBytes:bytes length:hexString.length/2];return newData;
}+(NSString *) parseByte2HexString:(Byte *) bytes
{NSMutableString *hexStr = [[NSMutableString alloc]init];int i = 0;if(bytes){while (bytes[i] != '\0'){NSString *hexByte = [NSString stringWithFormat:@"%x",bytes[i] & 0xff];///16进制数if([hexByte length]==1)[hexStr appendFormat:@"0%@", hexByte];else[hexStr appendFormat:@"%@", hexByte];i++;}}return hexStr;
}+(NSString *) parseByteArray2HexString:(Byte[]) bytes
{NSMutableString *hexStr = [[NSMutableString alloc]init];int i = 0;if(bytes){while (bytes[i] != '\0'){NSString *hexByte = [NSString stringWithFormat:@"%x",bytes[i] & 0xff];///16进制数if([hexByte length]==1)[hexStr appendFormat:@"0%@", hexByte];else[hexStr appendFormat:@"%@", hexByte];i++;}}return [hexStr uppercaseString];
}@end
NSString *keyString = @"bayilaoye#66#88";NSString *strString = @"我们都有一个家的权威的权威的权威的期望ccccMadison1234567890--";NSData *testData = [strString dataUsingEncoding: NSUTF8StringEncoding];//获取尺寸NSLog(@"加密前 资源数据strByte =:%@ \ndataLength =: %ld",strString,[strString length]);NSString *strParse = [DES stringWithHexBytes2:testData];NSLog(@"加密前 16进制数据strParse =:%@ \nstrParseLength =: %ld",strParse,[strParse length]);NSString * encryptBytes = [DES encryptUseDES:strString key:keyString];//加密NSLog(@"encryptBytes = %@ \nLength = :%ld", encryptBytes, [encryptBytes length]);NSString * decryptBytes = [DES decryptUseDES:encryptBytes key:keyString];//解密NSLog(@"decryptBytes = %@ \nLength =: %ld", decryptBytes, [decryptBytes length]);
<div><p></p></div>
这篇关于IOS 纯DES加密 与 使用base64加密的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!