2010-10-17 12 views
5

Mi piacerebbe avere una funzionalità di crittografia dei file per la mia applicazione iphone. Per le applicazioni desktop basate ho usato la funzione di seguito per crittografare i file relativamente piccoli:criptare un file su iphone-sdk

- (NSData *)aesEncrypt:(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; 
} 

Ma non credo che questo codice può essere utilizzato su un iPhone. Se provo a crittografare un file da 5mb ci vorrà almeno 10 mb in ram, dato che verrà caricato su NSData e restituito come tale. Esiste un metodo per eccryptare un file leggendo piccoli blocchi e scrivendo l'output su un altro file? O mi sbaglio su questo prendendo così m

+0

Ciao, sto anche lavorando con la crittografia in un'applicazione di cacao invece di iPhone. Come hai implementato il codice sopra con il file che hai usato per crittografare? Hai usato NDAlias? Non riesco a capire come afferrare il contenuto del file e quindi crittografarlo. –

+1

Ho rinunciato quindi sto solo leggendo un file su un buffer di dimensioni fisse, crittografando il buffer e scrivendo su un file crittografato. Sto facendo questo in un ciclo poiché il buffer è molto più piccolo del file stesso (per evitare i maiali della memoria) Funziona, ma non sono sicuro che non influenzi la forza della crittografia. – Marius

+0

Ciao Marius
hai funzionato? Sto anche facendo la stessa lettura del file nel buffer di dimensioni fisse quindi crittografando quel buffer. Ma quando provo a decriptare quel file crittografato, il risultato è un file corrotto. mi puoi aiutare? – Iducool

risposta