今天在做des加密的时候,在网上找到这段代码 挺好用的,demo测试没什么问题
//加密
-(NSString *)encryptUseDES:(NSString *)plainText andKey:(NSString *)authKey{
const void *iv = (const void *) [@"12345678" UTF8String];
NSString *ciphertext = nil;
NSData *textData = [plainText dataUsingEncoding:NSUTF8StringEncoding];
NSUInteger dataLength = [textData length];
NSInteger bufferLength = (dataLength/1024 +1)*1024;
unsigned char buffer[bufferLength];
memset(buffer, 0, sizeof(char) * bufferLength);
size_t numBytesEncrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt,
kCCAlgorithmDES,
kCCOptionPKCS7Padding,
[authKey UTF8String],
kCCKeySizeDES,
iv,
[textData bytes],
dataLength,
buffer,
bufferLength,
&numBytesEncrypted);
if (cryptStatus == kCCSuccess) {
NSData *data = [NSData dataWithBytes:buffer length:(NSUInteger)numBytesEncrypted];
ciphertext = [data base64EncodedStringWithOptions:0];
}
return ciphertext;
}
但是当我们加密长度大于1M的数据时 直接崩溃了
于是查询出来问题出在这里 创建的buffer 无法在内存中分配到足够大的内存
unsigned char buffer[bufferLength];
在大神的指点下换了一个分配方式解决了问题
unsigned char * buffer = (unsigned char *)malloc(bufferLength);
memset(buffer, 0, sizeof(char) * bufferLength);
记得最后释放内存
free(buffer);
完整代码如下
//加密
-(NSString *)encryptUseDES:(NSString *)plainText andKey:(NSString *)authKey{
const void *iv = (const void *) [@"12345678" UTF8String];
NSString *ciphertext = nil;
NSData *textData = [plainText dataUsingEncoding:NSUTF8StringEncoding];
NSUInteger dataLength = [textData length];
NSInteger bufferLength = (dataLength/1024 +1)*1024;
// unsigned char buffer[bufferLength];
unsigned char * buffer = (unsigned char *)malloc(bufferLength);
memset(buffer, 0, sizeof(char) * bufferLength);
size_t numBytesEncrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt,
kCCAlgorithmDES,
kCCOptionPKCS7Padding,
[authKey UTF8String],
kCCKeySizeDES,
iv,
[textData bytes],
dataLength,
buffer,
bufferLength,
&numBytesEncrypted);
if (cryptStatus == kCCSuccess) {
NSData *data = [NSData dataWithBytes:buffer length:(NSUInteger)numBytesEncrypted];
ciphertext = [data base64EncodedStringWithOptions:0];
}
free(buffer);
return ciphertext;
}