我正在尝试在文本编辑器中加密/解密纯文本文件。加密似乎工作正常,但解密不起作用,文本加密。我确信我已经使用我加密的单词解密了文本 - 有人可以通过下面的片段查看并帮助我吗?
谢谢:)
加密:
NSAlert *alert = [NSAlert alertWithMessageText:@"Encryption"
defaultButton:@"Set"
alternateButton:@"Cancel"
otherButton:nil
informativeTextWithFormat:@"Please enter a password to encrypt your file with:"];
[alert setIcon:[NSImage imageNamed:@"License.png"]];
NSSecureTextField *input = [[NSSecureTextField alloc] initWithFrame:NSMakeRect(0, 0, 300, 24)];
[alert setAccessoryView:input];
NSInteger button = [alert runModal];
if (button == NSAlertDefaultReturn) {
[[NSUserDefaults standardUserDefaults] setObject:[input stringValue] forKey:@"password"];
NSData *data;
[self setString:[textView textStorage]];
NSMutableDictionary *dict = [NSDictionary dictionaryWithObject:NSPlainTextDocumentType
forKey:NSDocumentTypeDocumentAttribute];
[textView breakUndoCoalescing];
data = [[self string] dataFromRange:NSMakeRange(0, [[self string] length])
documentAttributes:dict error:outError];
NSData*encrypt = [data AESEncryptWithPassphrase:[input stringValue]];
[encrypt writeToFile:[absoluteURL path] atomically:YES];
解密:
NSAlert *alert = [NSAlert alertWithMessageText:@"Decryption"
defaultButton:@"Open"
alternateButton:@"Cancel"
otherButton:nil
informativeTextWithFormat:@"This file has been protected with a password.To view its contents,enter the password below:"];
[alert setIcon:[NSImage imageNamed:@"License.png"]];
NSSecureTextField *input = [[NSSecureTextField alloc] initWithFrame:NSMakeRect(0, 0, 300, 24)];
[alert setAccessoryView:input];
NSInteger button = [alert runModal];
if (button == NSAlertDefaultReturn) {
NSLog(@"Entered Password - attempting to decrypt.");
NSMutableDictionary *dict = [NSDictionary dictionaryWithObject:NSPlainTextDocumentType
forKey:NSDocumentTypeDocumentOption];
NSData*decrypted = [[NSData dataWithContentsOfFile:[self fileName]] AESDecryptWithPassphrase:[input stringValue]];
mString = [[NSAttributedString alloc]
initWithData:decrypted options:dict documentAttributes:NULL
error:outError];
答案 0 :(得分:20)
为什么不使用内置加密算法?这是我写的NSData+AES,它使用CCCrypt和256位密钥进行AES256加密。
您可以像以下一样使用它:
NSData *data = [[NSData dataWithContentsOfFile:@"/etc/passwd"]
encryptWithString:@"mykey"];
并用以下内容解密:
NSData *file = [data decryptWithString:@"mykey"];
免责声明:不能保证NSData+AES没有错误:)这是相当新的。我欢迎代码审查。