【发布时间】:2011-08-11 02:19:57
【问题描述】:
我正在使用以下代码来加密 cocoa 中的文件:
- (NSData *)AES256EncryptWithKey:(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;
}
并为与文件的连接写了这个:
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"foo" ofType:@"rtf"];
NSData *data = [NSData dataWithContentsOfFile:filePath];
NSString *key = [withFileKey stringValue];
NSString *newStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSString *encrypted = [newStr AES256EncryptWithKey:key];
NSLog(@"File encryption:%@", encrypted);
[filePathName setStringValue:filePath];
if (!data) {
NSLog(@"Unable to read file");
}
基本上我所做的首先是获取用户想要的文件的文件路径。然后将文件中的数据转换为字符串。然后使用 AES256EncryptWithKey: 方法加密该字符串。但是,例如,当我解密纯文本文件时,它会返回一堆垃圾,例如字体和所有这些东西,然后是我写的几行。像这样的:
\ansicpg1252\cocoartf1138\cocoasubrtf100 {\fonttbl\f0\fswiss\fcharset0 Helvetica;\f1\fnil\fcharset0 Menlo-Bold;} {\colortbl;\red255\green255\blue255;} \margl1440\margr1440\vieww10800\viewh8400\viewkind0 \pard\tx720\tx1440\tx2160\tx2880\tx3600\tx4320\tx5040\tx5760\tx6480\tx7200\tx7920\tx8640\pardirnatural
\f0\fs24 \cf0 你好,我的名字是 bobby bob\ \ \pard\tx560\pardeftab560\pardirnatural
\f1\b\fs22 \cf0 \CocoaLigature0 耶!\ 我很棒!}
我不应该获取数据然后对其进行加密(转换为字节),然后转换加密数据并将其转换为要显示的字符串吗?我尝试了类似的方法,但没有奏效。 :(
类似:
NSData *encryptedData = [data AES256EncryptWithKey:yourkey];
然后:
NSString *convertData = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
? 非常感谢您的帮助。谢谢!
【问题讨论】:
标签: cocoa encryption encoding aes nsdata