////encryptanddecrypt.h#import <foundation/Foundation.h>@classNSString;@interfaceNSData (encryption)-(NSData*)Aes256encryptwithkey: (NSData*)Key//Encryption-(NSData*)Aes256decryptwithkey: (NSData*)Key//Decryption-(NSString*)Newstringinbase64fromdata;//Additional -Code + (NSString*)Base64Encode: (nsstring*)Str//Ditto -Code + (NSData*)Stringtobyte: (nsstring*)string;+ (NSString*)Bytetostring: (NSData*)Data@end
// encryptanddecrypt.m#import "EncryptAndDecrypt.h"#import <CommonCrypto/CommonCrypto.h>Static CharBase64[] ="abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz0123456789+/"; @implementation NSData (encryption)-(NSData *) Aes256encryptwithkey: (NSData *) key//Encryption{//aes256 encryption, the key should be 32-bit Const void* keyPtr2 = [key bytes];Char(*KEYPTR) [ +] = KEYPTR2;//For block encryption algorithms, the output size is always equal to or less than the input size plus the size of a block //So you need to add a block size to the bottomNsuinteger datalength = [self length]; size_t buffersize = datalength + kCCBlockSizeAES128;void*buffer = malloc (buffersize); size_t numbytesencrypted =0; Cccryptorstatus cryptstatus = Cccrypt (Kccencrypt, kCCAlgorithmAES128, Kccoptionpkcs7padding/ * Here's what we just said. Pkcs7padding Filled * /| Kccoptionecbmode, [key bytes], Kcckeysi zeAES256, NULL,/* Initialize vector (optional) */[Self bytes], datalength,/ * input * /Buffer, buffersize,/ * Output * /&numbytesencrypted);if(Cryptstatus = = kccsuccess) {return[NSData Datawithbytesnocopy:buffer length:numbytesencrypted]; } free (buffer);//Release buffer returnNil;} -(NSData *) Aes256decryptwithkey: (NSData *) key//Decryption{///or, in decryption, the key is also 32-bit Const void* keyPtr2 = [key bytes];Char(*KEYPTR) [ +] = KEYPTR2;//For block encryption algorithms, the output size is always equal to or less than the input size plus the size of a block //So you need to add a block size to the bottomNsuinteger datalength = [self length]; size_t buffersize = datalength + kCCBlockSizeAES128;void*buffer = malloc (buffersize); size_t numbytesdecrypted =0; Cccryptorstatus cryptstatus = Cccrypt (Kccdecrypt, kCCAlgorithmAES128, Kccoptionpkcs7padding/ * Here's what we just said. Pkcs7padding Filled * /| Kccoptionecbmode, Keyptr, kCCKeySizeAES25 6, NULL,/* Initialize vector (optional) */[Self bytes], datalength,/ * input * /Buffer, buffersize,/ * Output * /&numbytesdecrypted);if(Cryptstatus = = kccsuccess) {return[NSData Datawithbytesnocopy:buffer length:numbytesdecrypted]; } free (buffer);returnNil }-(NSString *) newstringinbase64fromdata//Append 64 encoding{nsmutablestring *dest = [[Nsmutablestring alloc] initwithstring:@""]; UnsignedChar* Working = (unsignedChar*) [self bytes];intSrclen = [self length]; for(intI=0; i<srclen; i + =3) { for(intnib=0; nib<4; nib++) {intByt = (NIB = =0)?0: nib-1;intIX = (nib+1)*2;if(I+byt >= Srclen) Break; UnsignedCharCurr = ((working[i+byt) << (8-ix)) &0x3F);if(I+nib < Srclen) Curr |= ((working[i+nib] >> ix) &0x3F); [Dest AppendFormat:@ "%c", Base64[curr]]; } }returnDest }+ (nsstring*) Base64Encode: (nsstring*) str{if([str length] = =0)return @"";Const Char*source = [Str utf8string];intStrlength = strlen (source);Char*characters = malloc ((strlength +2) /3) *4);if(characters = = NULL)returnNil Nsuinteger length =0; Nsuinteger i =0; while(I < Strlength) {Charbuffer[3] = {0,0,0}; ShortBufferlength =0; while(Bufferlength <3&& i < strlength) buffer[bufferlength++] = source[i++]; characters[length++] = base64[(buffer[0] &0xFC) >>2]; characters[length++] = base64[((buffer[0] &0x03) <<4) | ((buffer[1] &0xF0) >>4)];if(Bufferlength >1) characters[length++] = base64[((buffer[1] &0x0F) <<2) | ((buffer[2] &0xC0) >>6)];Elsecharacters[length++] =' = ';if(Bufferlength >2) characters[length++] = base64[buffer[2] &0x3F];Elsecharacters[length++] =' = '; } nsstring *g = [[NSString alloc] initwithbytesnocopy:characters length:length encoding:nsasciistringencoding FreeW Hendone:yes];returnG }+ (nsdata*) Stringtobyte: (nsstring*)string{NSString *hexstring=[[stringUppercasestring] Stringbyreplacingoccurrencesofstring:@" "Withstring:@""];if([HexString length]%2!=0) {returnNil } Byte tempbyt[1]={0}; nsmutabledata* Bytes=[nsmutabledata data]; for(intI=0; i<[hexstring length];i++) {Unichar hex_char1 = [hexstring characteratindex:i]; ////Two digit 16 decimal place First (high *16) intInt_ch1;if(Hex_char1 >=' 0 '&& hex_char1 <=' 9 ') Int_ch1 = (hex_char1- -)* -; ////0 of Ascll-48 Else if(Hex_char1 >=' A '&& hex_char1 <=' F ') Int_ch1 = (hex_char1- -)* -; Ascll-65 of//a Else returnNil i++; Unichar hex_char2 = [hexstring characteratindex:i]; ////Two bits 16 binary number second bit (low) intINT_CH2;if(Hex_char2 >=' 0 '&& hex_char2 <=' 9 ') Int_ch2 = (hex_char2- -); ////0 of Ascll-48 Else if(Hex_char2 >=' A '&& hex_char2 <=' F ') INT_CH2 = hex_char2- -; Ascll-65 of//a Else returnNil tempbyt[0] = INT_CH1+INT_CH2;///Convert The converted number into a byte array[Bytes appendbytes:tempbyt Length:1]; }returnbytes;} + (nsstring*) bytetostring: (nsdata*) data{Byte *plaintextbyte = (BYTE *) [data bytes]; NSString *hexstr=@""; for(intI=0; I<[data length];i++) {nsstring *newhexstr = [NSString stringWithFormat:@ "%x",plaintextbyte[i]&0xFF];/// 16 binary number if([Newhexstr length]==1) Hexstr = [NSString stringWithFormat:@ "%@0%@", Hexstr,newhexstr];ElseHEXSTR = [NSString stringWithFormat:@"%@%@", Hexstr,newhexstr]; }returnHexstr;} @end
Use
-(void) jiami{NSString*plaintext=@"AES China";//Clear text NSData *plaintextdata = [plaintext datausingencoding:nsutf8stringencoding]; NSString *keystr = @ "12345678901234567890123456789012"; NSData*keydatastr= [Keystr datausingencoding:nsutf8stringencoding]; NSData*ciphertextdata= [Plaintextdata aes256encryptwithkey:keydatastr]; NSString*hexstr= [NSData Bytetostring:ciphertextdata]; NSLog (@"Ciphertext:%@", hexstr); [Self jiemi:hexstr]; }-(void) Jiemi: (nsstring *)hexstring{nsstring *keystr = @ " 12345678901234567890123456789012 "; NSData*keydatastr= [Keystr datausingencoding:nsutf8stringencoding]; NSData*data= [NSData stringtobyte:hexstring];/////////////////NSData *datas = [data aes256decryptwithkey:keydatastr]; NSLog ([[[NSString Alloc]initwithdata:datas encoding:nsutf8stringencoding]);}
Transferred from: http://blog.csdn.net/zzzili/article/details/8610060