基本的单向加密算法:

BASE64 严格地说,属于编码格式,而非加密算法 
MD5(Message Digest algorithm 5,信息摘要算法)
SHA(Secure Hash Algorithm,安全散列算法)
HMAC(Hash Message Authentication Code,散列消息鉴别码)

MD5、SHA、HMAC这三种加密算法,可谓是非可逆加密,就是不可解密的加密方法。我们通常只把他们作为加密的基础。单纯的以上三种的加密并不可靠。

BASE64,按照RFC2045的定义,Base64被定义为:Base64内容传送编码被设计用来把任意序列的8位字节描述为一种不易被人直接识别的形式,常见于邮件、http加密,截取http信息,你就会发现登录操作的用户名、密码字段通过BASE64加密的。

复杂的对称加密(DES、PBE)、非对称加密算法:

DES(Data Encryption Standard,数据加密算法)    AES(高级加密标准)代替DES
  PBE(Password-based encryption,基于密码验证)
  RSA(算法的名字以发明者的名字命名:Ron Rivest, AdiShamir 和Leonard Adleman)
  DH(Diffie-Hellman算法,密钥一致协议)
  DSA(Digital Signature Algorithm,数字签名)
  ECC(Elliptic Curves Cryptography,椭圆曲线密码编码学)

iOS应用代码加密分为以下几种:

1)本地数据加密

对NSUserDefaults,sqlite存储文件数据加密,保护帐号和关键信息。

2)URL编码加密

对程序中出现的URL进行编码加密,防止URL被静态分析

3)网络传输数据加密

对客户端传输数据提供加密方案,有效防止通过网络接口的拦截获取

4)方法体,方法名高级混淆

对应用程序的方法名和方法体进行混淆,保证源码被逆向后无法解析代码

5)程序结构混排加密

对应用程序逻辑结构进行打乱混排,保证源码可读性降到最低

 

下面先介绍MD5:

先创建一个MD5文件,MD5.h
#import <Foundation/Foundation.h>

@interface MD5 : NSObject
+(NSString *)md5HexDigest:(NSString *)input;
@endMD5.m
#import "MD5.h"
#import <CommonCrypto/CommonDigest.h>

@implementation MD5

+(NSString *)md5HexDigest:(NSString *)input{

    const char* str = [input UTF8String];
    unsigned char result[CC_MD5_DIGEST_LENGTH]; //16位字节

    CC_MD5(str,(int)strlen(str),result);
    NSMutableString *ret = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH];
    
    for (int i = 0; i< CC_MD5_DIGEST_LENGTH; i++) {
        
        [ret appendFormat:@"%2s",result];
    }

    return ret;
}或者写另外的写法更直观一些:// 方法功能:md5 加密
+ (NSString *)md5:(NSString *)str
{
     
    const char *cStr = [str UTF8String];
    unsigned char result[16];
    CC_MD5(cStr, (CC_LONG)strlen(cStr), result); // This is the md5 call
    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]
            ];
}@end

 

ios调用MD5加密方式如下:

NSString *userName = @"cerastes";
NSString *password = @"hello Word";
//   MD5加密
NSString *md5 = [MD5 md5HexDigest:password];
NSLog(@"%@",md5);BASE64
base64图片转为base64:
 NSString *imageDocPath = [documentPath stringByAppendingPathComponent:@"FeekImageFile"];
 NSString *imagePath=[NSString stringWithFormat:@"%@/%@",imageDocPath,imageArry[i]];
 NSData *data=[[NSFileManager defaultManager] contentsAtPath:imagePath];
   //        NSData *data = UIImageJPEGRepresentation([UIImage imageNamed:@"icon_pic_no"], 1.0f);
  NSString *encodedImageStr = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];

base64的加密的使用:

使用之前,记得要有以下三个文件:

GTMDefines.h
GTMBase64.h
GTMBase64.m
下载地址:https://github.com/r258833095/GTMBase64
.h文件中代码如下
#import <Foundation/Foundation.h>
#import "GTMBase64.h"

@interface Base64 : NSObject

+(NSString *)encodeBase64String:(NSString *)input;
+(NSString *)decodeBase64String:(NSString *)input;

+(NSString *)encodeBase64Data:(NSData *)data;
+(NSString *)decodeBase64Data:(NSData *)data;
@end.m文件中代码如下
#import "Base64.h"

@implementation Base64


+(NSString *)encodeBase64String:(NSString *)input{

    NSData *data = [input dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
     data = [GTMBase64 encodeData:data];
    
    NSString *base64String = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    return base64String;

}
+(NSString *)decodeBase64String:(NSString *)input{

    NSData *data = [input dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
    
    data = [GTMBase64 decodeData:data];
    
    NSString *base64String = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    
    return base64String;

}

+(NSString *)encodeBase64Data:(NSData *)data{

    data = [GTMBase64 encodeData:data];
    NSString *base64String = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    
    return base64String;

}
+(NSString *)decodeBase64Data:(NSData *)data{

    data = [GTMBase64 decodeData:data];
    
    NSString *base64String = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    
    return base64String;}
@end

ios调用BASE64加密方式如下:

NSString *baseEncodeString = [GTMBase64 encodeBase64String:password];
NSString *baseDecodeString = [GTMBase64 decodeBase64String:baseEncodeString];NSLog(@"baseEncodeString = %@",baseEncodeString);
NSLog(@"baseDecodeString = %@",baseDecodeString); DES+GTMBase64的使用
 
+ (NSString *)encryptWithText:(NSString *)sText;//加密  
+ (NSString *)decryptWithText:(NSString *)sText;//解密 
.m文件中  (导包:#import"GTMBase64.h"(下面说)  #import<CommonCrypto/CommonCryptor.h>)



[cpp] view plain copy


1. + (NSString *)encryptWithText:(NSString *)sText  
2. {  
3. //kCCEncrypt 加密  
4. return [self encrypt:sText encryptOrDecrypt:kCCEncrypt key:@"des"];  
5. }  
6.   
7. + (NSString *)decryptWithText:(NSString *)sText  
8. {  
9. //kCCDecrypt 解密  
10. return [self encrypt:sText encryptOrDecrypt:kCCDecrypt key:@"des"];  
11. }  
12.   
13. + (NSString *)encrypt:(NSString *)sText encryptOrDecrypt:(CCOperation)encryptOperation key:(NSString *)key  
14. {  
15. const void *dataIn;  
16. size_t dataInLength;  
17.       
18. if (encryptOperation == kCCDecrypt)//传递过来的是decrypt 解码  
19.     {  
20. //解码 base64  
21. //转成utf-8并decode  
22.         dataInLength = [decryptData length];  
23.         dataIn = [decryptData bytes];  
24.     }  
25. else  //encrypt  
26.     {  
27.         NSData* encryptData = [sText dataUsingEncoding:NSUTF8StringEncoding];  
28.         dataInLength = [encryptData length];  
29. const void *)[encryptData bytes];  
30.     }  
31.       
32. /* 
33.      DES加密 :用CCCrypt函数加密一下,然后用base64编码下,传过去 
34.      DES解密 :把收到的数据根据base64,decode一下,然后再用CCCrypt函数解密,得到原本的数据 
35.      */  
36.     CCCryptorStatus ccStatus;  
37. //可以理解位type/typedef 的缩写(有效的维护了代码,比如:一个人用int,一个人用long。最好用typedef来定义)  
38. size_t dataOutAvailable = 0; //size_t  是操作符sizeof返回的结果类型  
39. size_t dataOutMoved = 0;  
40.       
41.     dataOutAvailable = (dataInLength + kCCBlockSizeDES) & ~(kCCBlockSizeDES - 1);  
42. sizeof(uint8_t));  
43. void *)dataOut, 0x0, dataOutAvailable);//将已开辟内存空间buffer的首 1 个字节的值设为值 0  
44.       
45. "12345678";  
46. const void *vkey = (const void *) [key UTF8String];  
47. const void *iv = (const void *) [initIv UTF8String];  
48.       
49. //CCCrypt函数 加密/解密  
50. //  加密/解密  
51. //  加密根据哪个标准(des,3des,aes。。。。)  
52. //  选项分组密码算法(des:对每块分组加一次密  3DES:对每块分组加三个不同的密)  
53. //密钥    加密和解密的密钥必须一致  
54. //   DES 密钥的大小(kCCKeySizeDES=8)  
55. //  可选的初始矢量  
56. // 数据的存储单元  
57. // 数据的大小  
58. void *)dataOut,// 用于返回数据  
59.                        dataOutAvailable,  
60.                        &dataOutMoved);  
61.       
62.     NSString *result = nil;  
63.       
64. if (encryptOperation == kCCDecrypt)//encryptOperation==1  解码  
65.     {  
66. //得到解密出来的data数据,改变为utf-8的字符串  
67. const void *)dataOut length:(NSUInteger)dataOutMoved] encoding:NSUTF8StringEncoding] autorelease];  
68.     }  
69. else //encryptOperation==0  (加密过程中,把加好密的数据转成base64的)  
70.     {  
71. //编码 base64  
72. const void *)dataOut length:(NSUInteger)dataOutMoved];  
73.         result = [GTMBase64 stringByEncodingData:data];  
74.     }  
75.       
76. return result;  
77. }


AES+GTMBase64的使用

#import <Foundation/Foundation.h> @interface DES3Util : NSObject
+ (NSString*) AES128Encrypt:(NSString *)plainText;
+ (NSString*) AES128Decrypt:(NSString *)encryptText;
@end

DES3Util.m文件内容



//
//  DES3Util.m
//  JuziAnalyticsDemo
//
//  Created by wanyakun on 13-6-6.
//  Copyright (c) 2013年 The9. All rights reserved.
//

#import "DES3Util.h"
#import <CommonCrypto/CommonCryptor.h>
#import "GTMBase64.h"

#define gkey			@"16位长度的字符串" //自行修改
#define gIv             @"16位长度的字符串" //自行修改

@implementation DES3Util

+(NSString *)AES128Encrypt:(NSString *)plainText
{
    char keyPtr[kCCKeySizeAES128+1];
    memset(keyPtr, 0, sizeof(keyPtr));
    [gkey getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
    
    char ivPtr[kCCBlockSizeAES128+1];
    memset(ivPtr, 0, sizeof(ivPtr));
    [gIv getCString:ivPtr maxLength:sizeof(ivPtr) encoding:NSUTF8StringEncoding];
    
    NSData* data = [plainText dataUsingEncoding:NSUTF8StringEncoding];
    NSUInteger dataLength = [data length];
    
    int diff = kCCKeySizeAES128 - (dataLength % kCCKeySizeAES128);
    int newSize = 0;
    
    if(diff > 0)
    {
        newSize = dataLength + diff;
    }
    
    char dataPtr[newSize];
    memcpy(dataPtr, [data bytes], [data length]);
    for(int i = 0; i < diff; i++)
    {
        dataPtr[i + dataLength] = 0x00;
    }
    
    size_t bufferSize = newSize + kCCBlockSizeAES128;
    void *buffer = malloc(bufferSize);
    memset(buffer, 0, bufferSize);
    
    size_t numBytesCrypted = 0;
    
    CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt,
                                          kCCAlgorithmAES128,
                                          0x0000,               //No padding
                                          keyPtr,
                                          kCCKeySizeAES128,
                                          ivPtr,
                                          dataPtr,
                                          sizeof(dataPtr),
                                          buffer,
                                          bufferSize,
                                          &numBytesCrypted);
    
    if (cryptStatus == kCCSuccess) {
        NSData *resultData = [NSData dataWithBytesNoCopy:buffer length:numBytesCrypted];
        return [GTMBase64 stringByEncodingData:resultData];
    }
    free(buffer);
    return nil;
}

+(NSString *)AES128Decrypt:(NSString *)encryptText
{    
    char keyPtr[kCCKeySizeAES128 + 1];
    memset(keyPtr, 0, sizeof(keyPtr));
    [gkey getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
    
    char ivPtr[kCCBlockSizeAES128 + 1];
    memset(ivPtr, 0, sizeof(ivPtr));
    [gIv getCString:ivPtr maxLength:sizeof(ivPtr) encoding:NSUTF8StringEncoding];
    
    NSData *data = [GTMBase64 decodeData:[encryptText dataUsingEncoding:NSUTF8StringEncoding]];
    NSUInteger dataLength = [data length];
    size_t bufferSize = dataLength + kCCBlockSizeAES128;
    void *buffer = malloc(bufferSize);
    
    size_t numBytesCrypted = 0;
    CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt,
                                          kCCAlgorithmAES128,
                                          0x0000,
                                          keyPtr,
                                          kCCBlockSizeAES128,
                                          ivPtr,
                                          [data bytes],
                                          dataLength,
                                          buffer,
                                          bufferSize,
                                          &numBytesCrypted);
    if (cryptStatus == kCCSuccess) {
        NSData *resultData = [NSData dataWithBytesNoCopy:buffer length:numBytesCrypted];
        return [[[NSString alloc] initWithData:resultData encoding:NSUTF8StringEncoding] autorelease];
    }
    free(buffer);
    return nil;
}


@end