iOS-AES对称加密

实验要求

  1. 编程语言不限制
  2. 明文“学号+姓名+专业+学院”
  3. 实现对明文的加密,输出密文
  4. 对密文实现解密,输出明文
  5. 不能是DES加密算法
  6. 报告中说明该语言提供的加密函数都有哪些,具体的使用方法并分析优缺点

代码

#import "ViewController.h"
#import "AES.h"
#import "NSString+AES.h"


@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //原文信息
    NSString *plainText = @"3180807001+黄振锋+计算机科学与技术+网络空间安全学院";
    //秘钥
    NSString *key = @"HuangZhenFeng";
    NSLog(@"纯加密:%@",[plainText AES256_Encrypt:key]);
    NSLog(@"纯解密:%@",[[plainText AES256_Encrypt:key] AES256_Decrypt:key]);

    //原文转码数据NSData
    NSData *plainData = [plainText dataUsingEncoding:NSUTF8StringEncoding];
    //用秘钥加密
    NSData *cipher = [plainData AES256EncryptWithKey:key];
    //得到密文
    NSLog(@"密文:%@",[cipher base64EncodedStringWithOptions:0]);
    
    //用秘钥解密
    NSData *cipher1 = [cipher AES256DecryptWithKey:key];
    //得到明文
    NSString *plainText1 = [[NSString alloc] initWithData:cipher1 encoding:NSUTF8StringEncoding];
    NSLog(@"明文:%@",plainText1);
}
#import "AES.h"
#import 
#import 

static char base64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

@implementation NSData (AES)

- (NSData *)AES256EncryptWithKey:(NSString *)key {
    // 'key' should be 32 bytes for AES256, will be null-padded otherwise
    char keyPtr[kCCKeySizeAES256+1]; // room for terminator (unused)
    bzero(keyPtr, sizeof(keyPtr)); // fill with zeroes (for padding)
    
    // fetch key data
    [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
    
    NSUInteger dataLength = [self length];
    
    //See the doc: For block ciphers, the output size will always be less than or
    //equal to the input size plus the size of one block.
    //That's why we need to add the size of one block here
    size_t bufferSize = dataLength + kCCBlockSizeAES128;
    void *buffer = malloc(bufferSize);
    
    size_t numBytesEncrypted =

你可能感兴趣的:(iOS-算法问题,AES,对称加密)