我想为我的 iPhone 应用程序提供文件加密功能。对于基于桌面的应用程序,我使用下面的函数来加密相对较小的文件:
- (NSData *)aesEncrypt:(NSString *)key {
// 'key' should be 32 bytes for AES256, will be null-padded otherwise
char keyPtr[kCCKeySizeAES256+1]; // room for terminator (unused)
bzero(keyPtr, sizeof(keyPtr)); // fill with zeroes (for padding)
// fetch key data
[key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
NSUInteger dataLength = [self length];
//See the doc: For block ciphers, the output size will always be less than or
//equal to the input size plus the size of one block.
//That's why we need to add the size of one block here
size_t bufferSize = dataLength + kCCBlockSizeAES128;
void *buffer = malloc(bufferSize);
size_t numBytesEncrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding,
keyPtr, kCCKeySizeAES256,
NULL /* initialization vector (optional) */,
[self bytes], dataLength, /* input */
buffer, bufferSize, /* output */
&numBytesEncrypted);
if (cryptStatus == kCCSuccess) {
//the returned NSData takes ownership of the buffer and will free it on deallocation
return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
}
free(buffer); //free the buffer;
return nil;
}
但我不认为这段代码可以在 iphone 上使用。如果我尝试加密一个 5mb 的文件,它将占用至少 10mb 的 ram,因为它将被加载到 NSData 并返回。有没有一种方法可以通过读取小块并将输出写入另一个文件来加密文件?还是我错了,所以 m
最佳答案
试试 RNCryptor https://github.com/rnapier/RNCryptor
我已经在我的应用中成功地使用了它。
关于iphone - 在 iphone-sdk 上加密文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3954707/