开发者

How to securely erase a file in iOS?

When I encrypt a file I want to overwrite its contents, not only delete i开发者_Go百科t. My intended purpose for this is to securely erase the file. Is there a way to do this in iOS?


Open the file memory mapped and overwrite the data, then delete the file using NSFileManager:

NSFileHandle *file = [NSFileHandle fileHandleForUpdatingAtPath: filename];
[file writeData: data];
[file closeFile];

Where data is an NSData object


Check NSFileManager:

- (BOOL)removeItemAtPath:(NSString *)path error:(NSError **)error

For example:

NSFileManager *manager = [NSFileManager defaultManager];
NSString *filePath;
NSError *error;
if ([manager fileExistsAtPath:filePath])
{
     [manager fileExistsAtPath:filePath error:&error];
     if (error)
     {
         NSLog(@"Error occured while [removing file]: \"%@\"\n",[error userInfo]);
     }
}

For writing in the same file:

NSOutputStream *fileStream = [NSOutputStream outputStreamToFileAtPath:filePath append:NO];
[fileStream open];
[fileStream write:&dataBytes maxLength:dataLength];
[fileStream close];

Where dataBytes is what you want to rewrite with.


To overwrite the old data, open the file using [NSFileHandle fileHandleForWritingAtPath:] (write-only access) or fileHandleForUpdatingAtPath: (read-write access). You can then either use the standard write with [myFileHandle fileDescriptor], or use [myFileHandle writeData:] to write a NSData object.

For deleting the overwritten file, use [[NSFileManager defaultManager] removeItemAtPath:].

As for what to write: I suggest you use a pre-generated a file of a convenient size (multiple of 512) and repeatedly overwrite your old file with the content of your "garbage data" file. Using the random number generator on iOS would only make sense for small files as it's too slow. You also don't gain any (serious) additional security by using random data, so you could as well overwrite the old file with a poem.


It is NOT necessary to overwrite a file multiple times. This is especially not necessary for Flash memory, as it will use a different block to write the new data anyway. But it's also NOT true for traditional hard drives. It's totally sufficient to oerwrite a file ONCE.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜