1. 程式人生 > >iOS資料的加密解密

iOS資料的加密解密

  • Base64編碼解碼:

  基於64個可列印的字元來表示二進位制資料的方法。

Base64編碼:

- (NSString *)encode:(NSString *)string
{
    //先將string轉換成data
    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
    
    NSData *base64Data = [data base64EncodedDataWithOptions:0];
    
    NSString *baseString = [[NSString alloc]initWithData:base64Data encoding:NSUTF8StringEncoding];
    
    
return baseString; }

  Base64解碼:

- (NSString *)dencode:(NSString *)base64String
{
    //NSData *base64data = [string dataUsingEncoding:NSUTF8StringEncoding];
    
    NSData *data = [[NSData alloc]initWithBase64EncodedString:base64String options:NSDataBase64DecodingIgnoreUnknownCharacters];
    
    NSString 
*string = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]; return string; }

 

 

  • MD5(Message Digest Algorithm 5:訊息摘要演算法第5版)

  MD5加密是從一段字串中通過相應特徵生成一段32位的數字字母混合碼。對輸入資訊生成唯一的固定的128位雜湊值(32個字元),即128個0和1的二進位制位,而在實際應用開發中,通常是以16進位制輸出的,所以正好就是32位的16進位制。MD5主要特點是 不可逆,相同資料的MD5值肯定一樣。

   注意點:

  (1)一定要和後臺開發人員約定好,MD5加密的位數是16位還是32位(大多數都是32位的),16位的可以通過32位的轉換得到。

  (2)MD5加密區分 大小寫,使用時要和後臺約定好。

MD5解密網站:http://www.cmd5.com/

 

  加密方法:

#[email protected] MD5Encrypt : NSObject
// MD5加密
/*
*由於MD5加密是不可逆的,多用來進行驗證
*/
// 32位小寫
+(NSString *)MD5ForLower32Bate:(NSString *)str;
// 32位大寫
+(NSString *)MD5ForUpper32Bate:(NSString *)str;
// 16為大寫
+(NSString *)MD5ForUpper16Bate:(NSString *)str;
// 16位小寫
+(NSString *)MD5ForLower16Bate:(NSString *)str;
@end
#import "MD5Encrypt.h"
#import <CommonCrypto/CommonDigest.h>

@implementation MD5Encrypt

#pragma mark - 32位 小寫
+(NSString *)MD5ForLower32Bate:(NSString *)str{
    
    //要進行UTF8的轉碼
    const char* input = [str UTF8String];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(input, (CC_LONG)strlen(input), result);
    
    NSMutableString *digest = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    for (NSInteger i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
        [digest appendFormat:@"%02x", result[i]];
    }
    
    return digest;
}

#pragma mark - 32位 大寫
+(NSString *)MD5ForUpper32Bate:(NSString *)str{
    
    //要進行UTF8的轉碼
    const char* input = [str UTF8String];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(input, (CC_LONG)strlen(input), result);
    
    NSMutableString *digest = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    for (NSInteger i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
        [digest appendFormat:@"%02X", result[i]];
    }
    
    return digest;
}

#pragma mark - 16位 大寫
+(NSString *)MD5ForUpper16Bate:(NSString *)str{
    
    NSString *md5Str = [self MD5ForUpper32Bate:str];
    
    NSString  *string;
    for (int i=0; i<24; i++) {
        string=[md5Str substringWithRange:NSMakeRange(8, 16)];
    }
    return string;
}


#pragma mark - 16位 小寫
+(NSString *)MD5ForLower16Bate:(NSString *)str{
    
    NSString *md5Str = [self MD5ForLower32Bate:str];
    
    NSString  *string;
    for (int i=0; i<24; i++) {
        string=[md5Str substringWithRange:NSMakeRange(8, 16)];
    }
    return string;
}

@end

 

  • AES256

   AES:高階加密標準(Advanced Encryption Standard)

    加密步驟: 字串經過AES加密得到NSData型別資料,然後在對加密後的NSData資料進行Base64轉碼,得出最終的字串

 

    解密步驟: 對要解密的字串進行Base64解碼得到NSData型別資料,然後對NSData資料經過AES解密,得出原字串

//建立一個基於NSObject的AESUtility類
#import <Foundation/Foundation.h>
 
@interface AESUtility : NSObject
+ (NSString *)EncryptString:(NSString *)sourceStr;
+ (NSString *)DecryptString:(NSString *)secretStr;
@end
#import "AESUtility.h"
 
#import <CommonCrypto/CommonDigest.h>
#import <CommonCrypto/CommonCryptor.h>
 
//加密與解密的祕鑰,保持與後臺的祕鑰相同
static NSString *key = @"12345678";
 
@implementation AESUtility
 
+ (NSString *)EncryptString:(NSString *)sourceStr
{
    char keyPtr[kCCKeySizeAES256 + 1];
    bzero(keyPtr, sizeof(keyPtr));
    [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
     
    NSData *sourceData = [sourceStr dataUsingEncoding:NSUTF8StringEncoding];
    NSUInteger dataLength = [sourceData length];
    size_t buffersize = dataLength + kCCBlockSizeAES128;
    void *buffer = malloc(buffersize);
    size_t numBytesEncrypted = 0;
    CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding | kCCOptionECBMode, keyPtr, kCCBlockSizeAES128, NULL, [sourceData bytes], dataLength, buffer, buffersize, &numBytesEncrypted);
     
    if (cryptStatus == kCCSuccess) {
        NSData *encryptData = [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
        //對加密後的二進位制資料進行base64轉碼
        return [encryptData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
    }
    else
    {
        free(buffer);
        return nil;
    }
}
 
+ (NSString *)DecryptString:(NSString *)secretStr
{
    //先對加密的字串進行base64解碼
    NSData *decodeData = [[NSData alloc] initWithBase64EncodedString:secretStr options:NSDataBase64DecodingIgnoreUnknownCharacters];
     
    char keyPtr[kCCKeySizeAES256 + 1];
    bzero(keyPtr, sizeof(keyPtr));
    [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
     
    NSUInteger dataLength = [decodeData length];
    size_t bufferSize = dataLength + kCCBlockSizeAES128;
    void *buffer = malloc(bufferSize);
    size_t numBytesDecrypted = 0;
    CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding | kCCOptionECBMode, keyPtr, kCCBlockSizeAES128, NULL, [decodeData bytes], dataLength, buffer, bufferSize, &numBytesDecrypted);
    if (cryptStatus == kCCSuccess) {
        NSData *data = [NSData dataWithBytesNoCopy:buffer length:numBytesDecrypted];
        NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        return result;
    }
    else
    {
        free(buffer);
        return nil;
    }
}
@end
注意點:
    1. 加密與解密的祕鑰key,需要與後臺協商共同定義,保持與後臺的祕鑰相同,也可以通過介面從後臺獲得;
    2. 匯入標頭檔案:#import <CommonCrypto/CommonDigest.h>和#import <CommonCrypto/CommonCryptor.h>

 

 

  • RSA