美文网首页iOS DeveloperIOS
iOS对称加密(AES与DES)

iOS对称加密(AES与DES)

作者: 一点就通 | 来源:发表于2017-08-16 08:32 被阅读0次

对称加密算法:指加密和解密使用相同密钥的加密算法(包括DES算法,3DES算法,RC5算法,AES算法等)。本文讲述AES算法和DES算法,AES和DES都包含两种加密算法的加密方式分别为ECB和CBC。

AES:高级加密标准,是美国联邦政府采用的一种区块加密标准。

DES:数据加密标准,(现在用的比较少,因为它的加密强度不够,能够暴力破解)。

ECB:电子密码本,就是每个块都是独立加密的。

CBC:密码块链,使用一个密钥和一个初始化向量(IV)对数据执行加密转换。

EncryptionTools.h 文件代码如下:

#import <Foundation/Foundation.h>
#import <CommonCrypto/CommonCrypto.h>
@interface EncryptionTools : NSObject

/**
 *  AES加密
 *
 *  @param string    要加密的字符串
 *  @param keyString 加密密钥
 *  @param iv        初始化向量(8个字节)
 *
 *  @return 返回加密后的base64编码字符串
 */
+ (NSString *)aesEncryptString:(NSString *)string keyString:(NSString *)keyString iv:(NSData *)iv;

/**
 *  AES解密
 *
 *  @param string    加密并base64编码后的字符串
 *  @param keyString 解密密钥
 *  @param iv        初始化向量(8个字节)
 *
 *  @return 返回解密后的字符串
 */
+ (NSString *)aesDecryptString:(NSString *)string keyString:(NSString *)keyString iv:(NSData *)iv;

/**
 *  DES加密
 *
 *  @param string    要加密的字符串
 *  @param keyString 加密密钥
 *  @param iv        初始化向量(8个字节)
 *
 *  @return 返回加密后的base64编码字符串
 */
+ (NSString *)desEncryptString:(NSString *)string keyString:(NSString *)keyString iv:(NSData *)iv;

/**
 *  DES解密
 *
 *  @param string    加密并base64编码后的字符串
 *  @param keyString 解密密钥
 *  @param iv        初始化向量(8个字节)
 *
 *  @return 返回解密后的字符串
 */
+ (NSString *)desDecryptString:(NSString *)string keyString:(NSString *)keyString iv:(NSData *)iv;

@end

EncryptionTools.m 文件代码如下:


#import "EncryptionTools.h"

@implementation EncryptionTools

//AES加密
+ (NSString *)aesEncryptString:(NSString *)string keyString:(NSString *)keyString iv:(NSData *)iv {
   // 设置秘钥
   NSData *keyData = [keyString dataUsingEncoding:NSUTF8StringEncoding];
   uint8_t cKey[kCCKeySizeAES128];
   bzero(cKey, sizeof(cKey));
   [keyData getBytes:cKey length:kCCKeySizeAES128];
   
   // 设置iv
   uint8_t cIv[kCCBlockSizeAES128];
   bzero(cIv, kCCBlockSizeAES128);
   int option = 0;
   if (iv) {
       [iv getBytes:cIv length:kCCBlockSizeAES128];
       option = kCCOptionPKCS7Padding;
   } else {
       option = kCCOptionPKCS7Padding | kCCOptionECBMode;
   }
   
   // 设置输出缓冲区
   NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
   size_t bufferSize = [data length] + kCCBlockSizeAES128;
   void *buffer = malloc(bufferSize);
   
   // 开始加密
   size_t encryptedSize = 0;
   
   /**
    @constant   kCCAlgorithmAES     高级加密标准,128位(默认)
    @constant   kCCAlgorithmDES     数据加密标准
    */
   CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt,
                                         kCCAlgorithmAES,
                                         option,
                                         cKey,
                                         kCCKeySizeAES128,
                                         cIv,
                                         [data bytes],
                                         [data length],
                                         buffer,
                                         bufferSize,
                                         &encryptedSize);
   
   NSData *result = nil;
   if (cryptStatus == kCCSuccess) {
       result = [NSData dataWithBytesNoCopy:buffer length:encryptedSize];
   } else {
       free(buffer);
       NSLog(@"[错误] 加密失败|状态编码: %d", cryptStatus);
   }
   
   return [result base64EncodedStringWithOptions:0];
}

//AES解密
+ (NSString *)aesDecryptString:(NSString *)string keyString:(NSString *)keyString iv:(NSData *)iv {
   // 设置秘钥
   NSData *keyData = [keyString dataUsingEncoding:NSUTF8StringEncoding];
   uint8_t cKey[kCCKeySizeAES128];
   bzero(cKey, sizeof(cKey));
   [keyData getBytes:cKey length:kCCKeySizeAES128];
   
   // 设置iv
   uint8_t cIv[kCCBlockSizeAES128];
   bzero(cIv, kCCBlockSizeAES128);
   int option = 0;
   if (iv) {
       [iv getBytes:cIv length:kCCBlockSizeAES128];
       option = kCCOptionPKCS7Padding;
   } else {
       option = kCCOptionPKCS7Padding | kCCOptionECBMode;
   }
   
   // 设置输出缓冲区,options参数很多地方是直接写0,但是在实际过程中可能出现回车的字符串导致解不出来
   NSData *data = [[NSData alloc] initWithBase64EncodedString:string options:NSDataBase64DecodingIgnoreUnknownCharacters];
   
   size_t bufferSize = [data length] + kCCBlockSizeAES128;
   void *buffer = malloc(bufferSize);
   
   // 开始解密
   size_t decryptedSize = 0;
   CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt,
                                         kCCAlgorithmAES128,
                                         option,
                                         cKey,
                                         kCCKeySizeAES128,
                                         cIv,
                                         [data bytes],
                                         [data length],
                                         buffer,
                                         bufferSize,
                                         &decryptedSize);
   
   NSData *result = nil;
   if (cryptStatus == kCCSuccess) {
       result = [NSData dataWithBytesNoCopy:buffer length:decryptedSize];
   } else {
       free(buffer);
       NSLog(@"[错误] 解密失败|状态编码: %d", cryptStatus);
   }
   
   return [[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding];
}

//DES加密
+ (NSString *)desEncryptString:(NSString *)string keyString:(NSString *)keyString iv:(NSData *)iv {
   // 设置秘钥
   NSData *keyData = [keyString dataUsingEncoding:NSUTF8StringEncoding];
   uint8_t cKey[kCCKeySizeDES];
   bzero(cKey, sizeof(cKey));
   [keyData getBytes:cKey length:kCCKeySizeDES];
   
   // 设置iv
   uint8_t cIv[kCCBlockSizeDES];
   bzero(cIv, kCCBlockSizeDES);
   int option = 0;
   if (iv) {
       [iv getBytes:cIv length:kCCBlockSizeDES];
       option = kCCOptionPKCS7Padding;
   } else {
       option = kCCOptionPKCS7Padding | kCCOptionECBMode;
   }
   
   // 设置输出缓冲区
   NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
   size_t bufferSize = [data length] + kCCBlockSizeDES;
   void *buffer = malloc(bufferSize);
   
   // 开始加密
   size_t encryptedSize = 0;
   
   CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt,
                                         kCCAlgorithmDES,
                                         option,
                                         cKey,
                                         kCCKeySizeDES,
                                         cIv,
                                         [data bytes],
                                         [data length],
                                         buffer,
                                         bufferSize,
                                         &encryptedSize);
   
   NSData *result = nil;
   if (cryptStatus == kCCSuccess) {
       result = [NSData dataWithBytesNoCopy:buffer length:encryptedSize];
   } else {
       free(buffer);
       NSLog(@"[错误] 加密失败|状态编码: %d", cryptStatus);
   }
   
   return [result base64EncodedStringWithOptions:0];
}

//DES解密
+ (NSString *)desDecryptString:(NSString *)string keyString:(NSString *)keyString iv:(NSData *)iv {
   // 设置秘钥
   NSData *keyData = [keyString dataUsingEncoding:NSUTF8StringEncoding];
   uint8_t cKey[kCCKeySizeDES];
   bzero(cKey, sizeof(cKey));
   [keyData getBytes:cKey length:kCCKeySizeDES];
   
   // 设置iv
   uint8_t cIv[kCCBlockSizeDES];
   bzero(cIv, kCCBlockSizeDES);
   int option = 0;
   if (iv) {
       [iv getBytes:cIv length:kCCBlockSizeDES];
       option = kCCOptionPKCS7Padding;
   } else {
       option = kCCOptionPKCS7Padding | kCCOptionECBMode;
   }
   
   // 设置输出缓冲区,options参数很多地方是直接写0,但是在实际过程中可能出现回车的字符串导致解不出来
   NSData *data = [[NSData alloc] initWithBase64EncodedString:string options:NSDataBase64DecodingIgnoreUnknownCharacters];

   size_t bufferSize = [data length] + kCCBlockSizeDES;
   void *buffer = malloc(bufferSize);
   
   // 开始解密
   size_t decryptedSize = 0;
   CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt,
                                         kCCAlgorithmDES,
                                         option,
                                         cKey,
                                         kCCKeySizeDES,
                                         cIv,
                                         [data bytes],
                                         [data length],
                                         buffer,
                                         bufferSize,
                                         &decryptedSize);
   
   NSData *result = nil;
   if (cryptStatus == kCCSuccess) {
       result = [NSData dataWithBytesNoCopy:buffer length:decryptedSize];
   } else {
       free(buffer);
       NSLog(@"[错误] 解密失败|状态编码: %d", cryptStatus);
   }
   
   return [[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding];
}

@end

ViewController.m 文件调用

#import "ViewController.h"
#import "EncryptionTools.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    //iv向量
    NSString *iv = @"abcdefghijklmnop";
    //转化为data,在java中是一个byte类型
    NSData *ivData = [iv dataUsingEncoding:NSUTF8StringEncoding];
    
    /****************************AES********************************/
    //aes-ecb加密, iv直接传nil就行
    NSString *aesEcbE = [EncryptionTools aesEncryptString:@"这个是AES-ECB加密" keyString:@"abcdefghi1234567" iv:nil];
    NSLog(@"aes-ecb加密: %@", aesEcbE);
    
    //aes-ecb解密, iv直接传nil就行
    NSString *aesEcbD = [EncryptionTools aesDecryptString:@"BKsrfQeUQnMEbPUxcbcy79Xuq4t2i04MgoFRDB8p7CI=" keyString:@"abcdefghi1234567" iv:nil];
    NSLog(@"aes-ecb解密: %@", aesEcbD);
    
    //aes-cbc加密
    NSString *aesCbcE = [EncryptionTools aesEncryptString:@"这个是AES-CBC加密" keyString:@"abcdefghi1234567" iv:ivData];
    NSLog(@"aes-cbc加密: %@", aesCbcE);
    
    //aes-cbc解密
    NSString *aesCbcD = [EncryptionTools aesDecryptString:@"eo9dQHISb7Uh6H7iYjPa5PyxaBfU1oFKdJiwJsqXIsg=" keyString:@"abcdefghi1234567" iv:ivData];
    NSLog(@"aes-cbc解密: %@", aesCbcD);
    
    /****************************DES********************************/
    
    //aes-ecb加密, iv直接传nil就行
    NSString *desEcbE = [EncryptionTools desEncryptString:@"这个是DES-ECB加密" keyString:@"abcdefghi1234567" iv:nil];
    NSLog(@"des-ecb加密: %@", desEcbE);
    
    //aes-ecb解密, iv直接传nil就行
    NSString *desEcbD = [EncryptionTools desDecryptString:@"fu2IYaT9ovofPt1trAt5nsgyPf16zJYB" keyString:@"abcdefghi1234567" iv:nil];
    NSLog(@"des-ecb解密: %@", desEcbD);
    
    //aes-cbc加密
    NSString *desCbcE = [EncryptionTools desEncryptString:@"这个是DES-ECB加密" keyString:@"abcdefghi1234567" iv:ivData];
    NSLog(@"des-cbc加密: %@", desCbcE);
    
    //aes-cbc解密
    NSString *desCbcD = [EncryptionTools desDecryptString:@"qqeY0KWFB6WikoZgtmiy9nrB8SLjsv90" keyString:@"abcdefghi1234567" iv:ivData];
    NSLog(@"des-cbc解密: %@", desCbcD);
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

打印结果如下:

Paste_Image.png

相关文章

网友评论

    本文标题:iOS对称加密(AES与DES)

    本文链接:https://www.haomeiwen.com/subject/mpevrxtx.html