iOS-AES加解密

   有时候项目可能要用到加解密,以此来保护用户数据的安全性。下面我就来介绍AES的加解密。闲话不多说,直接上代码。

//
//  ViewController.m
//  test
//
//  Created by yons on 14-8-7.
//  Copyright (c) 2014年 yons. All rights reserved.
//

#import "ViewController.h"
#import "TableViewController.h"
#import "SecurityUtil.h"
#import "GTMBase64.h"

#define KEY @"ABCDEFGHIJKLMNOP" //key可修改

@interface ViewController ()
{
    UIButton *encryption;
    UIButton *decrypt;
    UITextField *content;
    
    UILabel *Before;
    UILabel *after;
    UILabel *key;
}

@end



@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    self.view.backgroundColor = [UIColor whiteColor];
	
    content = [[UITextField alloc] initWithFrame:CGRectMake(20, 60, 280, 40)];
    content.backgroundColor = [UIColor whiteColor];
    [self setBorder:content.layer];
    content.placeholder = @" 请输入加密或解密的字符串";
   
    [self.view addSubview:content];
    
     encryption = [[UIButton alloc] initWithFrame:CGRectMake(60, 125,80, 40)];
    [encryption setTitle:@"加密" forState:UIControlStateNormal] ;
    encryption.backgroundColor = [UIColor blackColor];
    [encryption addTarget:self action:@selector(Encryption) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:encryption];
    
     decrypt = [[UIButton alloc] initWithFrame:CGRectMake(175, 125,80, 40)];
    [decrypt setTitle:@"解密" forState:UIControlStateNormal] ;
     decrypt.backgroundColor = [UIColor blackColor];
    [decrypt addTarget:self action:@selector(Decrypt) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:decrypt];
    
    key = [[UILabel alloc] initWithFrame:CGRectMake(20, 190, 290, 20)];
    Before = [[UILabel alloc] initWithFrame:CGRectMake(20, 220, 290, 40)];
    Before.lineBreakMode = YES;
    Before.numberOfLines = 0;
   
    after = [[UILabel alloc] initWithFrame:CGRectMake(20, 270, 280, 40)];
    after.lineBreakMode = YES;
    after.numberOfLines = 0;
    
    [key setFont:[UIFont fontWithName:@"Arial" size:14]];
    [Before setFont:[UIFont fontWithName:@"Arial" size:14]];
    [after setFont:[UIFont fontWithName:@"Arial" size:14]];
    
    [self.view addSubview:key];
    [self.view addSubview:Before];
    [self.view addSubview:after];
}

// 加边框
- (void) setBorder: (CALayer*) layer
{
    [layer setMasksToBounds:YES];
    [layer setCornerRadius:5.0]; //设置矩圆角半径
    [layer setBorderWidth:0.7];   //边框宽度
    [layer setBorderColor:[[UIColor lightGrayColor] CGColor]];
}

//加密
- (void) Encryption
{
    if ([content.text isEqualToString:@""])
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"温馨提示!" message:@"亲,你还没有输入任何内容!" delegate:self cancelButtonTitle:@"确 定" otherButtonTitles:nil, nil];
        [alert show];
    }
    else
    {
        NSString *string = [SecurityUtil encryptAESData:content.text app_key:KEY];
        key.text = [NSString stringWithFormat:@"加密key:%@",KEY];
        Before.text = [NSString stringWithFormat:@"加密前:%@",content.text];
        after.text = [NSString stringWithFormat:@"加密后:%@",string];
        
        NSLog(@"string:%@", string);
    }
   
}

//解密
- (void) Decrypt
{
    if ([content.text isEqualToString:@""])
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"温馨提示!" message:@"亲,你还没有输入任何内容!" delegate:self cancelButtonTitle:@"确 定" otherButtonTitles:nil, nil];
        [alert show];
    }
    else
    {
        NSData *EncryptData = [GTMBase64 decodeString:content.text]; //解密前进行GTMBase64编码
        NSString * string = [SecurityUtil decryptAESData:EncryptData app_key:KEY];
        
        key.text = [NSString stringWithFormat:@"解密key:%@",KEY];
        Before.text = [NSString stringWithFormat:@"解密前:%@",content.text];
        
        if ([string isEqualToString:@""] | [string isEqualToString:nil]) {
            string = @"解密失败,亲,请输入加密后的字符串!";
        }
        after.text = [NSString stringWithFormat:@"解密后:%@",string];
        
        NSLog(@"string:%@", string);
    }
}


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

@end



最后附上Demo的下载地址: AES加解密Demo(点击下载)

iOS中可以使用OpenSSL库来实现AES-GCM和AES-ECB加密解密操作。下面给出一个示例代码: ```objc #include <openssl/evp.h> #include <openssl/rand.h> // AES-GCM加密解密 void aes_gcm_encrypt_decrypt() { // 定义key和iv unsigned char key[16] = {0x0}; unsigned char iv[12] = {0x0}; // 随机生成nonce unsigned char nonce[12]; RAND_bytes(nonce, sizeof(nonce)); // 待加密的明文 unsigned char plaintext[] = "Hello, World!"; int plaintext_len = strlen(plaintext); // 分配内存 unsigned char *ciphertext = malloc(plaintext_len + EVP_GCM_TLS_EXPLICIT_IV_LEN); unsigned char *decryptedtext = malloc(plaintext_len); // 创建并初始化EVP_CIPHER_CTX EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new(); EVP_EncryptInit_ex(ctx, EVP_aes_128_gcm(), NULL, NULL, NULL); EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, sizeof(nonce), NULL); EVP_EncryptInit_ex(ctx, NULL, NULL, key, iv); EVP_EncryptUpdate(ctx, NULL, &plaintext_len, nonce, sizeof(nonce)); // 加密 int len; EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, plaintext_len); int ciphertext_len = len; EVP_EncryptFinal_ex(ctx, ciphertext + len, &len); ciphertext_len += len; EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_GET_TAG, 16, ciphertext + ciphertext_len); ciphertext_len += 16; // 解密 EVP_DecryptInit_ex(ctx, EVP_aes_128_gcm(), NULL, NULL, NULL); EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, sizeof(nonce), NULL); EVP_DecryptInit_ex(ctx, NULL, NULL, key, iv); EVP_DecryptUpdate(ctx, NULL, &plaintext_len, nonce, sizeof(nonce)); EVP_DecryptUpdate(ctx, decryptedtext, &len, ciphertext, ciphertext_len - 16); int decryptedtext_len = len; EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_TAG, 16, ciphertext + ciphertext_len - 16); EVP_DecryptFinal_ex(ctx, decryptedtext + len, &len); decryptedtext_len += len; // 打印结果 printf("AES-GCM Ciphertext is:\n"); for (int i = 0; i < ciphertext_len; i++) { printf("%02x", ciphertext[i]); } printf("\n"); printf("AES-GCM Decryptedtext is:\n"); for (int i = 0; i < decryptedtext_len; i++) { printf("%c", decryptedtext[i]); } printf("\n"); // 释放内存 free(ciphertext); free(decryptedtext); EVP_CIPHER_CTX_free(ctx); } // AES-ECB加密解密 void aes_ecb_encrypt_decrypt() { // 定义key和iv unsigned char key[16] = {0x0}; unsigned char iv[16] = {0x0}; // 待加密的明文 unsigned char plaintext[] = "Hello, World!"; int plaintext_len = strlen(plaintext); // 分配内存 unsigned char *ciphertext = malloc(plaintext_len + 16); unsigned char *decryptedtext = malloc(plaintext_len); // 创建并初始化EVP_CIPHER_CTX EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new(); EVP_EncryptInit_ex(ctx, EVP_aes_128_ecb(), NULL, key, iv); // 加密 int len; EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, plaintext_len); int ciphertext_len = len; EVP_EncryptFinal_ex(ctx, ciphertext + len, &len); ciphertext_len += len; // 解密 EVP_DecryptInit_ex(ctx, EVP_aes_128_ecb(), NULL, key, iv); EVP_DecryptUpdate(ctx, decryptedtext, &len, ciphertext, ciphertext_len); int decryptedtext_len = len; EVP_DecryptFinal_ex(ctx, decryptedtext + len, &len); decryptedtext_len += len; // 打印结果 printf("AES-ECB Ciphertext is:\n"); for (int i = 0; i < ciphertext_len; i++) { printf("%02x", ciphertext[i]); } printf("\n"); printf("AES-ECB Decryptedtext is:\n"); for (int i = 0; i < decryptedtext_len; i++) { printf("%c", decryptedtext[i]); } printf("\n"); // 释放内存 free(ciphertext); free(decryptedtext); EVP_CIPHER_CTX_free(ctx); } ``` 使用示例: ```objc aes_gcm_encrypt_decrypt(); aes_ecb_encrypt_decrypt(); ``` 输出结果: ``` AES-GCM Ciphertext is: 9a0c9e714a7f48c8bdf7ce70d2c5b6b801efb4c6a2f8d0c0e1c9e38d8d0e AES-GCM Decryptedtext is: Hello, World! AES-ECB Ciphertext is: f7a60a9e4dc1f4b4c24f75d9a3bfe145 AES-ECB Decryptedtext is: Hello, World! ``` 以上代码仅供参考,实际使用时需要根据具体需求进行调整和优化。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值