我試圖在我的文本編輯器中加密/解密純文本文件。加密似乎工作正常,但解密不起作用,文本加密。我確定我已經使用加密的文字解密了文本 - 有人能通過下面的代碼片段查看並幫助我嗎?可可中的NSData-AES類加密/解密
謝謝:)
加密:
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];
'-AESEncryptWithPassphrase:'和'-AESDecryptWithPassphrase:'方法來自哪裏? – 2010-04-06 04:21:55
嗨,羅布,我從這裏得到了NSData + AES類(包括這些方法):http://iphonedevelopment.blogspot.com/2009/02/strong-encryption-for-cocoa-cocoa-touch.html – Pripyat 2010-04-06 05:53:39
問題似乎在將keybits值更改爲128後自行修復。 – Pripyat 2010-04-06 10:44:19