Pri*_*yat 10 encryption cocoa nsdata
我试图在我的文本编辑器中加密/解密纯文本文件.加密似乎工作正常,但解密不起作用,文本加密.我确信我已经使用加密它的单词解密了文本 - 有人可以浏览下面的片段并帮助我吗?
谢谢 :)
加密:
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];
Run Code Online (Sandbox Code Playgroud)
解密:
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];
Run Code Online (Sandbox Code Playgroud)
nic*_*bot 20
为什么不使用内置加密算法?这里有一个NSData的+ AES我写它采用CCCrypt与AES256加密256it关键.
您可以像以下一样使用它:
NSData *data = [[NSData dataWithContentsOfFile:@"/etc/passwd"]
encryptWithString:@"mykey"];
Run Code Online (Sandbox Code Playgroud)
并解密它:
NSData *file = [data decryptWithString:@"mykey"];
Run Code Online (Sandbox Code Playgroud)
免责声明:不保证我的NSData + AES没有错误:)这是相当新的.我欢迎代码审查.