Search code examples
objective-csecuritymemoryswiftnsdata

Wipe NSData contents in Swift


I have an NSData object that will contain sensitive data. When the operation is complete, I would like to wipe the memory to avoid any potential security issues. In Objective-C, this is easy. I can just call...

memset([mySensitiveData bytes], 0, [mySensitiveData length]);

In Swift, however, it is not as straightforward. I tried the equivalent...

memset(mySensitiveData.bytes, 0, mySensitiveData.length)

...however, I get a compiler error saying...

'UnsafePointer<Void>' is not convertible to 'UnsafeMutablePointer<Void>'

Any idea how to get around this and wipe the memory safely in Swift? Thanks!!


Solution

  • NSData is immutable that's why it uses UnsafePointer<Void> for bytes pointer.

    You should use NSMutableData for this and then just call: resetBytesInRange(NSMakeRange(0, mySensitiveData.length)). This method will replace contents with zeroes as memset does.