AES128加密解密

最近项目中用到了aes128对某些后台接口url进行加密解密的问题这里特别说明一下
首先建一个NSdate的扩展类.h文件如下

#import

@classNSString;

@interfaceNSData (Encryption)

- (NSData*)AES128EncryptWithKey:(NSString*)key gIv:(NSString*)Iv;//加密

- (NSData*)AES128DecryptWithKey:(NSString*)key gIv:(NSString*)Iv;//解密

@end

然后是.m

#import"NSData+AES.h"

#import

@implementationNSData (Encryption)

//(key和iv向量这里是16位的)这里是CBC加密模式,安全性更高

- (NSData*)AES128EncryptWithKey:(NSString*)key gIv:(NSString*)Iv{
//加密

charkeyPtr[kCCKeySizeAES128+1];

bzero(keyPtr,sizeof(keyPtr));

[keygetCString:keyPtrmaxLength:sizeof(keyPtr)encoding:NSUTF8StringEncoding];

charivPtr[kCCKeySizeAES128+1];

memset(ivPtr,0,sizeof(ivPtr));

[IvgetCString:ivPtrmaxLength:sizeof(ivPtr)encoding:NSUTF8StringEncoding];

NSUIntegerdataLength = [selflength];

size_tbufferSize = dataLength +kCCBlockSizeAES128;

void*buffer =malloc(bufferSize);

size_tnumBytesEncrypted =0;

CCCryptorStatuscryptStatus =CCCrypt(kCCEncrypt,

kCCAlgorithmAES128,

kCCOptionPKCS7Padding,

keyPtr,

kCCBlockSizeAES128,

ivPtr,

[selfbytes],

dataLength,

buffer,

bufferSize,

&numBytesEncrypted);

if(cryptStatus ==kCCSuccess) {

return[NSDatadataWithBytesNoCopy:bufferlength:numBytesEncrypted];

}

free(buffer);

returnnil;

}

- (NSData*)AES128DecryptWithKey:(NSString*)key gIv:(NSString*)Iv{//解密

charkeyPtr[kCCKeySizeAES128+1];

bzero(keyPtr,sizeof(keyPtr));

[keygetCString:keyPtrmaxLength:sizeof(keyPtr)encoding:NSUTF8StringEncoding];

charivPtr[kCCKeySizeAES128+1];

memset(ivPtr,0,sizeof(ivPtr));

[IvgetCString:ivPtrmaxLength:sizeof(ivPtr)encoding:NSUTF8StringEncoding];

NSUIntegerdataLength = [selflength];

size_tbufferSize = dataLength +kCCBlockSizeAES128;

void*buffer =malloc(bufferSize);

size_tnumBytesDecrypted =0;

CCCryptorStatuscryptStatus =CCCrypt(kCCDecrypt,

kCCAlgorithmAES128,

kCCOptionPKCS7Padding,

keyPtr,

kCCBlockSizeAES128,

ivPtr,

[selfbytes],

dataLength,

buffer,

bufferSize,

&numBytesDecrypted);

if(cryptStatus ==kCCSuccess) {

return[NSDatadataWithBytesNoCopy:bufferlength:numBytesDecrypted];

}

free(buffer);

returnnil;

}

@end

其中iv向量,一般为公司内部约定好的偏移量,根据具体情况而定。其中大多数情况下aes会与base64结合使用。加密解密一般作为项目中的问题不会太复杂。

你可能感兴趣的:(AES128加密解密)