首页 > 代码库 > IOS开发各种加解密,编解码

IOS开发各种加解密,编解码

1.AES加解密,给NSData添加类别 NSData+AES

   添加头文件#import <CommonCrypto/CommonCryptor.h>

- (NSData *)AES256EncryptWithKey:(NSString *)key {//加密

    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 {//解密
    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编解码参考

GTMDefines.h
GTMBase64.h
GTMBase64.m

下载地址

http://code.google.com/p/google-toolbox-for-mac/source/browse/trunk/Foundation/?r=87

http://code.google.com/p/google-toolbox-for-mac/source/browse/trunk/Foundation/?r=575


3.各种加密,数字摘要。给NSString添加类别NSString+Encrypto

(1).MD5数字摘要

- (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",
            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摘要

- (NSString*) sha1
{
    const char *cstr = [self cStringUsingEncoding:NSUTF8StringEncoding];
    NSData *data = http://www.mamicode.com/[NSData dataWithBytes:cstr length:self.length];>

(3)base64编码
- (NSString *) base64
{    
    NSData * data = [self dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]; 
    data = [GTMBase64 encodeData:data]; 
    NSString * output = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; 
    return output; 
}

(4)SHA1与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)MD5与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:CC_MD5_DIGEST_LENGTH];
    base64 = [GTMBase64 encodeData:base64];
 
    NSString * output = [[NSString alloc] initWithData:base64 encoding:NSUTF8StringEncoding]; 
    return output;
}

4.3DES是一种对称的加密方式,因为用的同一个密钥。

对于加解密的安全性什么大家可以google,baidu自己找资料参考。

我也不过是简单的说一下通信加密中的一种可实现方案而已。

同样的3DES加密基本也都是统一的,系统也直接提供了API,基本代码如下

//3des加解密  
+ (NSString*)TripleDES:(NSString*)plainText encryptOrDecrypt:(CCOperation)encryptOrDecrypt  
{   
    const void *vplainText;  
    size_t plainTextBufferSize;  
      
    if (encryptOrDecrypt == kCCDecrypt)//解密  
    {  
        NSData *EncryptData = [GTMBase64 decodeData:[plainText dataUsingEncoding:NSUTF8StringEncoding]];  
        plainTextBufferSize = [EncryptData length];  
        vplainText = [EncryptData bytes];  
    }  
    else //加密  
    {  
        NSData* data = http://www.mamicode.com/[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 *) [DESKEY 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 = http://www.mamicode.com/[NSData dataWithBytes:(const void *)bufferPtr length:(NSUInteger)movedBytes];
        result = [GTMBase64 stringByEncodingData:myData];  
    }  
      
    return result;  
}

IOS开发各种加解密,编解码