iOS下 AES128加密算法
因为蓝牙4.0芯片自带AES128加密算法所以 只要涉及到蓝牙开发都会使用
加密方法
+(NSMutableData*)AES_NEW_AESEn:(NSMutableData*)plain pass:(NSMutableData*)key
{
// NSLog(@"key是%@",key);
charkeyPtr[kCCKeySizeAES128+1];
memset(keyPtr,0,sizeof(keyPtr));
[keygetBytes:keyPtrlength:sizeof(keyPtr)];
//NSLog(@"加密的KEY是%s",keyPtr);
NSData* data = [[NSDataalloc]initWithData:plain];
NSUIntegerdataLength = [datalength];
size_tbufferSize = dataLength +kCCBlockSizeAES128;
void*buffer =malloc(bufferSize);
size_tnumBytesEncrypted =0;
CCCryptorStatuscryptStatus =CCCrypt(kCCEncrypt,
kCCAlgorithmAES128,
kCCOptionPKCS7Padding|kCCOptionECBMode,
keyPtr,
kCCBlockSizeAES128,
NULL,
[databytes],
dataLength,
buffer,
bufferSize,
&numBytesEncrypted);
if(cryptStatus ==kCCSuccess) {
NSMutableData*resultData = [NSMutableDatadataWithBytes:bufferlength:numBytesEncrypted];
returnresultData;
}
free(buffer);
returnnil;
}
解密方法
+(NSMutableData*)AES_NEW_AESDecrypt:(NSMutableData*)encryptText password:(NSMutableData*)key
{
charkeyPtr[kCCKeySizeAES128+1];
memset(keyPtr,0,sizeof(keyPtr));
[keygetBytes:keyPtrlength:sizeof(keyPtr)];
NSData*data=[[NSDataalloc]initWithData:encryptText];
NSUIntegerdataLength = [datalength];
size_tbufferSize = dataLength +kCCBlockSizeAES128;
void*buffer =malloc(bufferSize);
size_tnumBytesCrypted =0;
CCCryptorStatuscryptStatus =CCCrypt(kCCDecrypt,
kCCAlgorithmAES128,
kCCOptionECBMode,
keyPtr,
kCCBlockSizeAES128,
NULL,
[databytes],
dataLength,
buffer,
bufferSize,
&numBytesCrypted);
if(cryptStatus ==kCCSuccess) {
NSMutableData*resultData = [NSMutableDatadataWithBytesNoCopy:bufferlength:numBytesCrypted];
returnresultData;
}
free(buffer);
returnnil;
}
解密的时候没带 kCCOptionPKCS7Padding 如果发现需要就加上