2010-04-05 8 views
9

Estoy intentando cifrar/descifrar un archivo de texto plano en mi editor de texto. El encriptado parece funcionar bien, pero el descifrado no funciona, el texto aparece encriptado. Estoy seguro de que he descifrado el texto usando la palabra con la que lo cifré. ¿Podría alguien mirar el siguiente fragmento y ayudarme?Cifrado/descifrado de clase NSData-AES en Cocoa

Gracias :)

de cifrado:

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]; 

Decodificación:

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

¿De dónde vienen los métodos '-AESEncryptWithPassphrase:' y '-AESDecryptWithPassphrase:'? –

+0

Hola Rob, obtuve la clase NSData + AES (que incluye estos métodos) desde aquí: http: //iphonedevelopment.blogspot.com/2009/02/strong-encryption-for-cocoa-cocoa-touch.html – Pripyat

+0

el problema parece haberse arreglado después de cambiar el valor de los keybits a 128. – Pripyat

Respuesta

20

por qué no utilizar el incorporado en los algoritmos de cifrado? Aquí hay un NSData+AES que escribí que usa CCCrypt con una clave 256it para el cifrado AES256.

Se puede utilizar como:

NSData *data = [[NSData dataWithContentsOfFile:@"/etc/passwd"] 
          encryptWithString:@"mykey"]; 

y descifrar con:

NSData *file = [data decryptWithString:@"mykey"]; 

AVISO: No hay garantía de mi NSData+AES es libre de errores :) Es bastante nuevo. Doy la bienvenida a revisiones de código.

+0

gracias. He codificado algo como esto hace un tiempo, también está codificado uno que funciona con NSMutableDictionary - impresionante para License Property Files;) – Pripyat

+0

¿Hay sales en el cifrado proporcionado @nicerobot? –

+0

@TwoDumpling Hay un soporte para un vector inicial proporcionado por CCCrypt pero sal simplemente se agrega al texto que se va a cifrar. – nicerobot