iOS的各种加密方法使用简介

来源:互联网 发布:sql express 安装失败 编辑:程序博客网 时间:2024/05/17 03:34

1.base64加密:

[objc] view plain copy
  1. <span style="font-size:14px;">//  
  2. //  base64Test.m  
  3. //  base64test  
  4. //  
  5. //  Created by apple on 15/6/30.  
  6. //  Copyright (c) 2015年 meishidiandian. All rights reserved.  
  7. //  
  8.   
  9. #import "base64Test.h"  
  10.   
  11.   
  12. //引入IOS自带密码库  
  13. #import <CommonCrypto/CommonCryptor.h>  
  14.   
  15. //空字符串  
  16. #define     LocalStr_None           @""  
  17.   
  18. static const char encodingTable[] = "";  
  19.   
  20.   
  21. @implementation base64Test  
  22.   
  23. + (NSString *)base64StringFromText:(NSString *)text  
  24. {  
  25.     if (text && ![text isEqualToString:LocalStr_None]) {  
  26.         //取项目的bundleIdentifier作为KEY  改动了此处  
  27.         //NSString *key = [[NSBundle mainBundle] bundleIdentifier];  
  28.         NSData *data = [text dataUsingEncoding:NSUTF8StringEncoding];  
  29.         //IOS 自带DES加密 Begin  改动了此处  
  30.         //data = [self DESEncrypt:data WithKey:key];  
  31.         //IOS 自带DES加密 End  
  32.         return [self base64EncodedStringFrom:data];  
  33.     }  
  34.     else {  
  35.         return LocalStr_None;  
  36.     }  
  37. }  
  38.   
  39. + (NSString *)textFromBase64String:(NSString *)base64  
  40. {  
  41.     if (base64 && ![base64 isEqualToString:LocalStr_None]) {  
  42.         //取项目的bundleIdentifier作为KEY   改动了此处  
  43.         //NSString *key = [[NSBundle mainBundle] bundleIdentifier];  
  44.         NSData *data = [self dataWithBase64EncodedString:base64];  
  45.         //IOS 自带DES解密 Begin    改动了此处  
  46.         //data = [self DESDecrypt:data WithKey:key];  
  47.         //IOS 自带DES加密 End  
  48.         return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];  
  49.     }  
  50.     else {  
  51.         return LocalStr_None;  
  52.     }  
  53. }  
  54.   
  55. /****************************************************************************** 
  56.  函数名称 : + (NSData *)DESEncrypt:(NSData *)data WithKey:(NSString *)key 
  57.  函数描述 : 文本数据进行DES加密 
  58.  输入参数 : (NSData *)data 
  59.  (NSString *)key 
  60.  输出参数 : N/A 
  61.  返回参数 : (NSData *) 
  62.  备注信息 : 此函数不可用于过长文本 
  63.  ******************************************************************************/  
  64. + (NSData *)DESEncrypt:(NSData *)data WithKey:(NSString *)key  
  65. {  
  66.     char keyPtr[kCCKeySizeAES256+1];  
  67.     bzero(keyPtr, sizeof(keyPtr));  
  68.       
  69.     [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];  
  70.       
  71.     NSUInteger dataLength = [data length];  
  72.       
  73.     size_t bufferSize = dataLength + kCCBlockSizeAES128;  
  74.     voidvoid *buffer = malloc(bufferSize);  
  75.       
  76.     size_t numBytesEncrypted = 0;  
  77.     CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmDES,  
  78.                                           kCCOptionPKCS7Padding | kCCOptionECBMode,  
  79.                                           keyPtr, kCCBlockSizeDES,  
  80.                                           NULL,  
  81.                                           [data bytes], dataLength,  
  82.                                           buffer, bufferSize,  
  83.                                           &numBytesEncrypted);  
  84.     if (cryptStatus == kCCSuccess) {  
  85.         return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];  
  86.     }  
  87.       
  88.     free(buffer);  
  89.     return nil;  
  90. }  
  91.   
  92. /****************************************************************************** 
  93.  函数名称 : + (NSData *)DESEncrypt:(NSData *)data WithKey:(NSString *)key 
  94.  函数描述 : 文本数据进行DES解密 
  95.  输入参数 : (NSData *)data 
  96.  (NSString *)key 
  97.  输出参数 : N/A 
  98.  返回参数 : (NSData *) 
  99.  备注信息 : 此函数不可用于过长文本 
  100.  ******************************************************************************/  
  101. + (NSData *)DESDecrypt:(NSData *)data WithKey:(NSString *)key  
  102. {  
  103.     char keyPtr[kCCKeySizeAES256+1];  
  104.     bzero(keyPtr, sizeof(keyPtr));  
  105.       
  106.     [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];  
  107.       
  108.     NSUInteger dataLength = [data length];  
  109.       
  110.     size_t bufferSize = dataLength + kCCBlockSizeAES128;  
  111.     voidvoid *buffer = malloc(bufferSize);  
  112.       
  113.     size_t numBytesDecrypted = 0;  
  114.     CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, kCCAlgorithmDES,  
  115.                                           kCCOptionPKCS7Padding | kCCOptionECBMode,  
  116.                                           keyPtr, kCCBlockSizeDES,  
  117.                                           NULL,  
  118.                                           [data bytes], dataLength,  
  119.                                           buffer, bufferSize,  
  120.                                           &numBytesDecrypted);  
  121.       
  122.     if (cryptStatus == kCCSuccess) {  
  123.         return [NSData dataWithBytesNoCopy:buffer length:numBytesDecrypted];  
  124.     }  
  125.       
  126.     free(buffer);  
  127.     return nil;  
  128. }  
  129.   
  130. /****************************************************************************** 
  131.  函数名称 : + (NSData *)dataWithBase64EncodedString:(NSString *)string 
  132.  函数描述 : base64格式字符串转换为文本数据 
  133.  输入参数 : (NSString *)string 
  134.  输出参数 : N/A 
  135.  返回参数 : (NSData *) 
  136.  备注信息 : 
  137.  ******************************************************************************/  
  138. + (NSData *)dataWithBase64EncodedString:(NSString *)string  
  139. {  
  140.     if (string == nil)  
  141.         [NSException raise:NSInvalidArgumentException format:nil];  
  142.     if ([string length] == 0)  
  143.         return [NSData data];  
  144.       
  145.     static charchar *decodingTable = NULL;  
  146.     if (decodingTable == NULL)  
  147.     {  
  148.         decodingTable = malloc(256);  
  149.         if (decodingTable == NULL)  
  150.             return nil;  
  151.         memset(decodingTable, CHAR_MAX, 256);  
  152.         NSUInteger i;  
  153.         for (i = 0; i < 64; i++)  
  154.             decodingTable[(short)encodingTable[i]] = i;  
  155.     }  
  156.       
  157.     const charchar *characters = [string cStringUsingEncoding:NSASCIIStringEncoding];  
  158.     if (characters == NULL)     //  Not an ASCII string!  
  159.         return nil;  
  160.     charchar *bytes = malloc((([string length] + 3) / 4) * 3);  
  161.     if (bytes == NULL)  
  162.         return nil;  
  163.     NSUInteger length = 0;  
  164.       
  165.     NSUInteger i = 0;  
  166.     while (YES)  
  167.     {  
  168.         char buffer[4];  
  169.         short bufferLength;  
  170.         for (bufferLength = 0; bufferLength < 4; i++)  
  171.         {  
  172.             if (characters[i] == '\0')  
  173.                 break;  
  174.             if (isspace(characters[i]) || characters[i] == '=')  
  175.                 continue;  
  176.             buffer[bufferLength] = decodingTable[(short)characters[i]];  
  177.             if (buffer[bufferLength++] == CHAR_MAX)      //  Illegal character!  
  178.             {  
  179.                 free(bytes);  
  180.                 return nil;  
  181.             }  
  182.         }  
  183.           
  184.         if (bufferLength == 0)  
  185.             break;  
  186.         if (bufferLength == 1)      //  At least two characters are needed to produce one byte!  
  187.         {  
  188.             free(bytes);  
  189.             return nil;  
  190.         }  
  191.           
  192.         //  Decode the characters in the buffer to bytes.  
  193.         bytes[length++] = (buffer[0] << 2) | (buffer[1] >> 4);  
  194.         if (bufferLength > 2)  
  195.             bytes[length++] = (buffer[1] << 4) | (buffer[2] >> 2);  
  196.         if (bufferLength > 3)  
  197.             bytes[length++] = (buffer[2] << 6) | buffer[3];  
  198.     }  
  199.       
  200.     bytes = realloc(bytes, length);  
  201.     return [NSData dataWithBytesNoCopy:bytes length:length];  
  202. }  
  203.   
  204. /****************************************************************************** 
  205.  函数名称 : + (NSString *)base64EncodedStringFrom:(NSData *)data 
  206.  函数描述 : 文本数据转换为base64格式字符串 
  207.  输入参数 : (NSData *)data 
  208.  输出参数 : N/A 
  209.  返回参数 : (NSString *) 
  210.  备注信息 : 
  211.  ******************************************************************************/  
  212. + (NSString *)base64EncodedStringFrom:(NSData *)data  
  213. {  
  214.     if ([data length] == 0)  
  215.         return @"";  
  216.       
  217.     charchar *characters = malloc((([data length] + 2) / 3) * 4);  
  218.     if (characters == NULL)  
  219.         return nil;  
  220.     NSUInteger length = 0;  
  221.       
  222.     NSUInteger i = 0;  
  223.     while (i < [data length])  
  224.     {  
  225.         char buffer[3] = {0,0,0};  
  226.         short bufferLength = 0;  
  227.         while (bufferLength < 3 && i < [data length])  
  228.             buffer[bufferLength++] = ((charchar *)[data bytes])[i++];  
  229.           
  230.         //  Encode the bytes in the buffer to four characters, including padding "=" characters if necessary.  
  231.         characters[length++] = encodingTable[(buffer[0] & 0xFC) >> 2];  
  232.         characters[length++] = encodingTable[((buffer[0] & 0x03) << 4) | ((buffer[1] & 0xF0) >> 4)];  
  233.         if (bufferLength > 1)  
  234.             characters[length++] = encodingTable[((buffer[1] & 0x0F) << 2) | ((buffer[2] & 0xC0) >> 6)];  
  235.         else characters[length++] = '=';  
  236.         if (bufferLength > 2)  
  237.             characters[length++] = encodingTable[buffer[2] & 0x3F];  
  238.         else characters[length++] = '=';  
  239.     }  
  240.       
  241.     return [[NSString alloc] initWithBytesNoCopy:characters length:length encoding:NSASCIIStringEncoding freeWhenDone:YES];  
  242. }  
  243.   
  244.   
  245. @end</span><span style="font-size: 18px;">  
  246. </span>  



2.md5+sha1加密:


[objc] view plain copy
  1. //md5 encode  
  2. +(NSString *) md5:(NSString *)str  
  3. {  
  4.     const charchar *cStr = [str UTF8String];  
  5.     unsigned char digest[CC_MD5_DIGEST_LENGTH];  
  6.     CC_MD5( cStr, (unsigned int)strlen(cStr), digest );  
  7.       
  8.     NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];  
  9.       
  10.     for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)  
  11.         [output appendFormat:@"%02X", digest[i]];  
  12.       
  13.     return output;  
  14. }  
  15. //sha1 encode  
  16. +(NSString*) sha1:(NSString *)str  
  17. {  
  18.     const charchar *cstr = [str cStringUsingEncoding:NSUTF8StringEncoding];  
  19.     NSData *data = [NSData dataWithBytes:cstr length:str.length];  
  20.       
  21.     uint8_t digest[CC_SHA1_DIGEST_LENGTH];  
  22.       
  23.     CC_SHA1(data.bytes, (unsigned int)data.length, digest);  
  24.       
  25.     NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];  
  26.       
  27.     for(int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++)  
  28.         [output appendFormat:@"%02x", digest[i]];  
  29.       
  30.     return output;  
  31. }  


3.aes256位 加密和解密:


[objc] view plain copy
  1. #import "NSData+AES256.h"  
  2. #define PASSWORD @"feng5.cn12345678"  
  3.   
  4. static const char encodingTable[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";  
  5. const NSUInteger kAlgorithmKeySize = kCCKeySizeAES256;  
  6. const NSUInteger kPBKDFRounds = 10000;  // ~80ms on an iPhone 4  
  7.   
  8. static Byte saltBuff[] = {0,1,2,3,4,5,6,7,8,9,0xA,0xB,0xC,0xD,0xE,0xF};  
  9.   
  10. static Byte ivBuff[]   = {0xA,1,0xB,5,4,0xF,7,9,0x17,3,1,6,8,0xC,0xD,91};  
  11.   
  12. @implementation NSData (AES256)  
  13.   
  14. + (NSData *)AESKeyForPassword:(NSString *)password{                  //Derive a key from a text password/passphrase  
  15.       
  16.     NSMutableData *derivedKey = [NSMutableData dataWithLength:kAlgorithmKeySize];  
  17.       
  18.     NSData *salt = [NSData dataWithBytes:saltBuff length:kCCKeySizeAES128];  
  19.       
  20.     int result = CCKeyDerivationPBKDF(kCCPBKDF2,        // algorithm算法  
  21.                                   password.UTF8String,  // password密码  
  22.                                   password.length,      // passwordLength密码的长度  
  23.                                   salt.bytes,           // salt内容  
  24.                                   salt.length,          // saltLen长度  
  25.                                   kCCPRFHmacAlgSHA1,    // PRF  
  26.                                   kPBKDFRounds,         // rounds循环次数  
  27.                                   derivedKey.mutableBytes// derivedKey  
  28.                                   derivedKey.length);   // derivedKeyLen derive:出自  
  29.       
  30.     NSAssert(result == kCCSuccess,  
  31.              @"Unable to create AES key for spassword: %d", result);  
  32.     return derivedKey;  
  33. }  
  34.   
  35. /*加密方法*/  
  36. + (NSString *)AES256EncryptWithPlainText:(NSString *)plain {  
  37.     NSData *plainText = [plain dataUsingEncoding:NSUTF8StringEncoding];  
  38.     // 'key' should be 32 bytes for AES256, will be null-padded otherwise  
  39.     char keyPtr[kCCKeySizeAES256+1]; // room for terminator (unused)  
  40.     bzero(keyPtr, sizeof(keyPtr)); // fill with zeroes (for padding)  
  41.           
  42.     NSUInteger dataLength = [plainText length];  
  43.   
  44.     size_t bufferSize = dataLength + kCCBlockSizeAES128;  
  45.     voidvoid *buffer = malloc(bufferSize);  
  46.     bzero(buffer, sizeof(buffer));  
  47.       
  48.     size_t numBytesEncrypted = 0;  
  49.       
  50.     CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmAES128,kCCOptionPKCS7Padding,  
  51.                                           [[NSData AESKeyForPassword:PASSWORD] bytes], kCCKeySizeAES256,  
  52.                                           NULL /* initialization vector (optional) */,  
  53.                                           [plainText bytes], dataLength, /* input */  
  54.                                           buffer, bufferSize, /* output */  
  55.                                           &numBytesEncrypted);  
  56.     if (cryptStatus == kCCSuccess) {  
  57.         NSData *encryptData = [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];  
  58.         return [encryptData base64EncodedStringWithOptions:0];  
  59.     }  
  60.       
  61.     free(buffer); //free the buffer;  
  62.     return nil;  
  63. }  
  64.   
  65. /*解密方法*/  
  66. + (NSString *)AES256DecryptWithCiphertext:(NSString *)ciphertexts{  
  67.       
  68.     NSData *cipherData = [NSData dataWithBase64EncodedString:ciphertexts];  
  69.     // 'key' should be 32 bytes for AES256, will be null-padded otherwise  
  70.     char keyPtr[kCCKeySizeAES256+1]; // room for terminator (unused)  
  71.     bzero(keyPtr, sizeof(keyPtr)); // fill with zeroes (for padding)  
  72.           
  73.     NSUInteger dataLength = [cipherData length];  
  74.       
  75.     size_t bufferSize = dataLength + kCCBlockSizeAES128;  
  76.     voidvoid *buffer = malloc(bufferSize);  
  77.           
  78.     size_t numBytesDecrypted = 0;  
  79.     CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding,  
  80.                                           [[NSData AESKeyForPassword:PASSWORD] bytes], kCCKeySizeAES256,   
  81.                                           NULL ,/* initialization vector (optional) */  
  82.                                           [cipherData bytes], dataLength, /* input */  
  83.                                           buffer, bufferSize, /* output */  
  84.                                           &numBytesDecrypted);  
  85.       
  86.     if (cryptStatus == kCCSuccess) {  
  87.         NSData *encryptData = [NSData dataWithBytesNoCopy:buffer length:numBytesDecrypted];  
  88.         return [[NSString alloc] initWithData:encryptData encoding:NSUTF8StringEncoding] ;  
  89.     }  
  90.       
  91.     free(buffer); //free the buffer;  
  92.     return nil;  
  93. }  
  94.   
  95. + (id)dataWithBase64EncodedString:(NSString *)string;  
  96. {  
  97.     if (string == nil)  
  98.         [NSException raise:NSInvalidArgumentException format:nil];  
  99.     if ([string length] == 0)  
  100.         return [NSData data];  
  101.       
  102.     static charchar *decodingTable = NULL;  
  103.     if (decodingTable == NULL)  
  104.     {  
  105.         decodingTable = malloc(256);  
  106.         if (decodingTable == NULL)  
  107.             return nil;  
  108.         memset(decodingTable, CHAR_MAX, 256);  
  109.         NSUInteger i;  
  110.         for (i = 0; i < 64; i++)  
  111.             decodingTable[(short)encodingTable[i]] = i;  
  112.     }  
  113.       
  114.     const charchar *characters = [string cStringUsingEncoding:NSASCIIStringEncoding];  
  115.     if (characters == NULL)     //  Not an ASCII string!  
  116.         return nil;  
  117.     charchar *bytes = malloc((([string length] + 3) / 4) * 3);  
  118.     if (bytes == NULL)  
  119.         return nil;  
  120.     NSUInteger length = 0;  
  121.       
  122.     NSUInteger i = 0;  
  123.     while (YES)  
  124.     {  
  125.         char buffer[4];  
  126.         short bufferLength;  
  127.         for (bufferLength = 0; bufferLength < 4; i++)  
  128.         {  
  129.             if (characters[i] == '\0')  
  130.                 break;  
  131.             if (isspace(characters[i]) || characters[i] == '=')  
  132.                 continue;  
  133.             buffer[bufferLength] = decodingTable[(short)characters[i]];  
  134.             if (buffer[bufferLength++] == CHAR_MAX)      //  Illegal character!  
  135.             {  
  136.                 free(bytes);  
  137.                 return nil;  
  138.             }  
  139.         }  
  140.           
  141.         if (bufferLength == 0)  
  142.             break;  
  143.         if (bufferLength == 1)      //  At least two characters are needed to produce one byte!  
  144.         {  
  145.             free(bytes);  
  146.             return nil;  
  147.         }  
  148.           
  149.         //  Decode the characters in the buffer to bytes.  
  150.         bytes[length++] = (buffer[0] << 2) | (buffer[1] >> 4);  
  151.         if (bufferLength > 2)  
  152.             bytes[length++] = (buffer[1] << 4) | (buffer[2] >> 2);  
  153.         if (bufferLength > 3)  
  154.             bytes[length++] = (buffer[2] << 6) | buffer[3];  
  155.     }  
  156.       
  157.     bytes = realloc(bytes, length);  
  158.     return [NSData dataWithBytesNoCopy:bytes length:length];  
  159. }  
0 0