加密:
//加密
+(NSString*)AES128Encrypt:(NSString*)plainText key:(NSString*)key
{
char keyPtr[kCCKeySizeAES128+1];
memset(keyPtr,0,sizeof(keyPtr));
[keygetCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
NSData* data = [plainText dataUsingEncoding:NSUTF8StringEncoding];
NSUIntegerdataLength = [datalength];
size_tbufferSize = dataLength +kCCBlockSizeAES128;
void*buffer =malloc(bufferSize);
size_tnumBytesEncrypted =0;
CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt,
kCCAlgorithmAES128,
kCCOptionPKCS7Padding|kCCOptionECBMode,
keyPtr,
kCCBlockSizeAES128,
NULL,
[databytes],
dataLength,
buffer,
bufferSize,
&numBytesEncrypted);
if(cryptStatus ==kCCSuccess) {
NSData*resultData = [NSDatadataWithBytesNoCopy:bufferlength:numBytesEncrypted];
NSString*baseStr_GTM = [selfencodeBase64Data:resultData];
returnbaseStr_GTM;
}
free(buffer);
return nil;
}
//解密
+(NSString*)AES128Decrypt:(NSString*)encryptText key:(NSString*)key
{
charkeyPtr[kCCKeySizeAES128+1];
memset(keyPtr,0,sizeof(keyPtr));
[keygetCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
NSData *data1 = [encryptText dataUsingEncoding:NSUTF8StringEncoding];
NSData*baseData_GTM = [selfdecodeBase64Data:data1];
NSUIntegerdataLength = [baseData_GTMlength];
size_tbufferSize = dataLength +kCCBlockSizeAES128;
void*buffer =malloc(bufferSize);
size_tnumBytesCrypted =0;
CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt,
kCCAlgorithmAES128,
kCCOptionPKCS7Padding|kCCOptionECBMode,
keyPtr,
kCCBlockSizeAES128,
NULL,
[baseData_GTMbytes],
dataLength,
buffer,
bufferSize,
&numBytesCrypted);
if(cryptStatus ==kCCSuccess) {
NSData*resultData = [NSDatadataWithBytesNoCopy:bufferlength:numBytesCrypted];
return [[NSString alloc] initWithData:resultData encoding:NSUTF8StringEncoding];
}
free(buffer);
return nil;
}
/**< GTMBase64编码 */
+ (NSString*)encodeBase64Data:(NSData*)data {
data = [GTMBase64encodeData:data];
NSString *base64String = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
returnbase64String;
}
/**< GTMBase64解码 */
+ (NSData*)decodeBase64Data:(NSData*)data {
data = [GTMBase64decodeData:data];
returndata;
}
第一次写简书,不好请谅解和指出,以后多多改正和学习!
最后,GTMBase64两个文件直接在网上找下,或者直接加我QQ624216132.
参考:https://www.jianshu.com/p/c05d6fc8ccc2
https://www.jianshu.com/p/8460f32daf00
网友评论