swift实现AES解密
Posted 罗小浮
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了swift实现AES解密相关的知识,希望对你有一定的参考价值。
原来的加密解密是用java写的,用在安卓系统上。现在要用在ios系统上,所以从服务器上下载过来的加密文件要用swift来实现其的解密方法。
具体过程如下:
给NSData增加一个类目,NSData+AES
NSData+AES.h
- (NSData *)AES128DecryptWithKey:(NSString *)key iv:(NSData *)iv;
NSData+AES.m
- (NSData *)AES128operation:(CCOperation)operation key:(NSString *)key iv:(NSData *)iv
{
char keyPtr[kCCKeySizeAES128 + 1];
bzero(keyPtr, sizeof(keyPtr));
[key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
Byte key2[] = {0xF0,0x1E,0x02,0xB2,0xE3,0xC9,0x7A,0x43,0xFD,0xFE,0x31,0x1A,0x2B,0xA4,0x4C,0x60};
// IV
Byte ivPtr[kCCBlockSizeAES128 + 1];
bzero(ivPtr, sizeof(ivPtr));
//[iv getCString:ivPtr maxLength:sizeof(ivPtr) encoding:NSUTF8StringEncoding];
[iv getBytes:&ivPtr length:16];
size_t bufferSize = [self length] + kCCBlockSizeAES128;
void *buffer = malloc(bufferSize);
size_t numBytesEncrypted = 0;
CCCryptorStatus cryptorStatus = CCCrypt(operation, kCCAlgorithmAES128, kCCOptionPKCS7Padding,
key2, kCCKeySizeAES128,
ivPtr,
[self bytes], [self length],
buffer, bufferSize,
&numBytesEncrypted);
if(cryptorStatus == kCCSuccess){
NSLog(@"Success");
return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
}else{
NSLog(@"Error");
}
free(buffer);
return nil;
}
以上是关于swift实现AES解密的主要内容,如果未能解决你的问题,请参考以下文章