Implementation of AES encryption on iOS

Source: Internet
Author: User

Encryption. h file
 
 
 
 
 
# Import <Foundation/Foundation. h>
 
 
 
@ Class NSString;
 
 
 
@ Interface NSData (Encryption)
 
 
 
-(NSData *) AES256EncryptWithKey :( NSString *) key; // Encryption
 
-(NSData *) AES256DecryptWithKey :( NSString *) key; // decrypt
 
-(NSString *) newStringInBase64FromData; // append 64 Encoding
 
+ (NSString *) base64encode :( NSString *) str; // same as the preceding 64 Encoding
 
 
 
@ End
 
 
 
Bytes ------------------------------------------------------------------------------------------------
 
 
 
Encryption. m file
 
 
 
# Import "Encryption. h"
 
# Import <CommonCrypto/CommonCryptor. h>
 
 
 
 
 
Static char base64 [] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 + /";
 
 
 
@ Implementation NSData (Encryption)
 
 
 
-(NSData *) AES256EncryptWithKey :( NSString *) key // Encryption
 
{
 
Char keyPtr [kCCKeySizeAES256 + 1];
 
Bzero (keyPtr, sizeof (keyPtr ));
 
[Key getCString: keyPtr maxLength: sizeof (keyPtr) encoding: NSUTF8StringEncoding];
 
NSUInteger dataLength = [self length];
 
Size_t bufferSize = dataLength + kCCBlockSizeAES128;
 
Void * buffer = malloc (bufferSize );
 
Size_t numBytesEncrypted = 0;
 
CCCryptorStatus cryptStatus = CCCrypt (kCCEncrypt, kCCAlgorithmAES128,
 
KCCOptionPKCS7Padding | kCCOptionECBMode,
 
KeyPtr, kCCBlockSizeAES128,
 
NULL,
 
[Self bytes], dataLength,
 
Buffer, bufferSize,
 
& NumBytesEncrypted );
 
If (cryptStatus = kCCSuccess ){
 
Return [NSData dataWithBytesNoCopy: buffer length: numBytesEncrypted];
 
}
 
Free (buffer );
 
Return nil;
 
}
 
 
 
 
 
-(NSData *) AES256DecryptWithKey :( NSString *) key // decryption
 
{
 
Char keyPtr [kCCKeySizeAES256 + 1];
 
Bzero (keyPtr, sizeof (keyPtr ));
 
[Key getCString: keyPtr maxLength: sizeof (keyPtr) encoding: NSUTF8StringEncoding];
 
NSUInteger dataLength = [self length];
 
Size_t bufferSize = dataLength + kCCBlockSizeAES128;
 
Void * buffer = malloc (bufferSize );
 
Size_t numBytesDecrypted = 0;
 
CCCryptorStatus cryptStatus = CCCrypt (kCCDecrypt, kCCAlgorithmAES128,
 
KCCOptionPKCS7Padding | kCCOptionECBMode,
 
KeyPtr, kCCBlockSizeAES128,
 
NULL,
 
[Self bytes], dataLength,
 
Buffer, bufferSize,
 
& NumBytesDecrypted );
 
If (cryptStatus = kCCSuccess ){
 
Return [NSData dataWithBytesNoCopy: buffer length: numBytesDecrypted];
 
}
 
Free (buffer );
 
Return nil;
 
}
 
 
 
 
 
-(NSString *) newStringInBase64FromData // append 64 Encoding
 
{
 
NSMutableString * dest = [[NSMutableString alloc] initWithString: @ ""];
 
Unsigned char * working = (unsigned char *) [self bytes];
 
Int srcLen = [self length];
 
For (int I = 0; I <srcLen; I + = 3 ){
 
For (int nib = 0; nib <4; nib ++ ){
 
Int byt = (nib = 0 )? 0: nib-1;
 
Int ix = (nib + 1) * 2;
 
If (I + byt> = srcLen) break;
 
Unsigned char curr = (working [I + byt] <(8-ix) & 0x3F );
 
If (I + nib <srcLen) curr | = (working [I + nib]> ix) & 0x3F );
 
[Dest appendFormat: @ "% c", base64 [curr];
 
}
 
}
 
Return dest;
 
}
 
 
 
+ (NSString *) base64encode :( NSString *) str
 
{
 
If ([str length] = 0)
 
Return @"";
 
Const char * source = [str UTF8String];
 
Int strlength = strlen (source );
 
Char * characters = malloc (strlength + 2)/3) * 4 );
 
If (characters = NULL)
 
Return nil;
 
NSUInteger length = 0;
 
NSUInteger I = 0;
 
While (I <strlength ){
 
Char buffer [3] = {0, 0 };
 
Short bufferLength = 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)];
 
Else characters [length ++] = ';
 
If (bufferLength> 2)
 
Characters [length ++] = base64 [buffer [2] & 0x3F];
 
Else characters [length ++] = ';
 
}
 
NSString * g = [[NSString alloc] initWithBytesNoCopy: characters length: length encoding: NSASCIIStringEncoding freeWhenDone: YES] autorelease];
 
Return g;
 
}
 
 
 
 
 
@ End
 
 
 
Bytes ------------------------------------------------------------------------------------------------
 
 
 
Test code
 
 
 
 
 
# Import "Encryption. h"
 
 
 
 
 
 
 
 
 
NSString * key = @ "my password ";
 
NSString * secret = @ "text to encrypt ";
 
// Encryption
 
NSData * plain = [secret dataUsingEncoding: NSUTF8StringEncoding];
 
NSData * cipher = [plain AES256EncryptWithKey: key];
 
NSLog (@ "% @", [[cipher newStringInBase64FromData] autorelease]);
 
Printf ("% s \ n", [[cipher description] UTF8String]);
 
NSLog (@ "% @", [[[NSString alloc] initWithData: cipher encoding: NSUTF8StringEncoding] autorelease]); // print out null because no decryption is performed.
 
// Decrypt
 
Plain = [cipher AES256DecryptWithKey: key];
 
Printf ("% s \ n", [[plain description] UTF8String]);
 
NSLog (@ "% @", [[[NSString alloc] initWithData: plain encoding: NSUTF8StringEncoding] autorelease]);
// Print the secret and use the password to decrypt it. If the wrong password is used, null is printed.

Download

 
Http://www.bkjia.com/uploadfile/2012/0201/20120201063624325.rar

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.