When I encrypt a file I want to overwrite its contents, not only delete it. My intended purpose for this is to securely erase the file. Is there a way to do this in iOS?
问题:
回答1:
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
回答2:
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.
回答3:
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.
回答4:
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.