Various encryption and decryption and codec for IOS development

Source: Internet
Author: User

Various encryption and decryption and codec for IOS development

1. AES encryption and decryption: Add NSData + AES to NSData

Add header file # import

-(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;

}

 

2. base64 encoding/decoding reference

GTMDefines. h
GTMBase64.h
GTMBase64.m

 


3. Various encryption and digital summarization. Add category NSString + Encrypto to NSString

(1). MD5 digital digest

-(NSString *) md5 {

Const char * cStr = [self UTF8String];
Unsigned char result [16];
CC_MD5 (cStr, strlen (cStr), result );
Return [NSString stringWithFormat: @ % 02X % 02X % 02X % 02X % 02X % 02X % 02X % 02X % 02X % 02X % 02X % 02X % 02X % 02X % 02X % 02X % 02X,
Result [0], result [1], result [2], result [3],
Result [4], result [5], result [6], result [7],
Result [8], result [9], result [10], result [11],
Result [12], result [13], result [14], result [15]
];
}

 

(2) SHA1 Abstract

 

- (NSString*) sha1{    const char *cstr = [self cStringUsingEncoding:NSUTF8StringEncoding];    NSData *data = [NSData dataWithBytes:cstr length:self.length];     uint8_t digest[CC_SHA1_DIGEST_LENGTH];     CC_SHA1(data.bytes, data.length, digest);     NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];     for(int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++)        [output appendFormat:@%02x, digest[i]];     return output;}
 
(3) base64 encoding
- (NSString *) base64{        NSData * data = [self dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];     data = [GTMBase64 encodeData:data];     NSString * output = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];     return output; }
 
(4) combination of SHA1 and base64
- (NSString *) sha1_base64{    const char *cstr = [self cStringUsingEncoding:NSUTF8StringEncoding];    NSData *data = [NSData dataWithBytes:cstr length:self.length];     uint8_t digest[CC_SHA1_DIGEST_LENGTH];     CC_SHA1(data.bytes, data.length, digest);     NSData * base64 = [[NSData alloc]initWithBytes:digest length:CC_SHA1_DIGEST_LENGTH];    base64 = [GTMBase64 encodeData:base64];     NSString * output = [[NSString alloc] initWithData:base64 encoding:NSUTF8StringEncoding];     return output; } 
(5) combination of MD5 and base64-(NSString *) md5_base64 {const char * cStr = [self UTF8String]; unsigned char digest [CC_MD5_DIGEST_LENGTH]; CC_MD5 (cStr, strlen (cStr ), digest); NSData * base64 = [[NSData alloc] initWithBytes: digest length: bytes]; base64 = [GTMBase64 encodeData: base64]; NSString * output = [[NSString alloc] initWithData: base64 encoding: NSUTF8StringEncoding]; return output ;}

 

4.3DES is a symmetric encryption method because the same key is used.

For information about encryption and decryption security, refer to google and baidu.

I am simply talking about a feasible solution in communication encryption.

The same 3DES encryption is basically uniform, and the system also provides APIs directly. The basic code is as follows:

// 3des encryption and decryption
+ (NSString *) TripleDES :( NSString *) plainText encryptOrDecrypt :( CCOperation) encryptOrDecrypt
{
Const void * vplainText;
Size_t plainTextBufferSize;

If (encryptOrDecrypt = kCCDecrypt) // decrypt
{
NSData * EncryptData = [GTMBase64 decodeData: [plainText dataUsingEncoding: NSUTF8StringEncoding];
PlainTextBufferSize = [EncryptData length];
VplainText = [EncryptData bytes];
}
Else // Encryption
{
NSData * data = [plainText dataUsingEncoding: NSUTF8StringEncoding];
PlainTextBufferSize = [data length];
VplainText = (const void *) [data bytes];
}

CCCryptorStatus ccStatus;
Uint8_t * bufferPtr = NULL;
Size_t bufferPtrSize = 0;
Size_t movedBytes = 0;

BufferPtrSize = (plainTextBufferSize + kCCBlockSize3DES )&~ (KCCBlockSize3DES-1 );
BufferPtr = malloc (bufferPtrSize * sizeof (uint8_t ));
Memset (void *) bufferPtr, 0x0, bufferPtrSize );
// Memset (void *) iv, 0x0, (size_t) sizeof (iv ));

Const void * vkey = (const void *) [cipher ey UTF8String];
// NSString * initVec = @ init Vec;
// Const void * vinitVec = (const void *) [initVec UTF8String];
// Byte iv [] = {0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
CcStatus = CCCrypt (encryptOrDecrypt,
KCCAlgorithm3DES,
KCCOptionPKCS7Padding | kCCOptionECBMode,
Vkey,
KCCKeySize3DES,
Nil,
VplainText,
PlainTextBufferSize,
(Void *) bufferPtr,
BufferPtrSize,
& MovedBytes );
// If (ccStatus = kCCSuccess) NSLog (@ SUCCESS );
/* Else if (ccStatus = kCC ParamError) return @ param error;
Else if (ccStatus = kCCBufferTooSmall) return @ buffer too small;
Else if (ccStatus = kCCMemoryFailure) return @ memory failure;
Else if (ccStatus = kCCAlignmentError) return @ ALIGNMENT;
Else if (ccStatus = kCCDecodeError) return @ decode error;
Else if (ccStatus = kCCUnimplemented) return @ UNIMPLEMENTED ;*/

NSString * result;

If (encryptOrDecrypt = kCCDecrypt)
{
Result = [[[NSString alloc] initWithData: [NSData dataWithBytes :( const void *) bufferPtr
Length :( NSUInteger) movedBytes]
Encoding: NSUTF8StringEncoding]
Autorelease];
}
Else
{
NSData * myData = [NSData dataWithBytes :( const void *) bufferPtr length :( NSUInteger) movedBytes];
Result = [GTMBase64 stringByEncodingData: myData];
}

Return result;
}

Related Article

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.