Search code examples
pythonstringsecuritymemorylanguage-implementation

Completely erase object from memory in python


Using python, I've encountered an interesting problem: my script reads some sensitive info, and I want the data completely scrubbed as soon as it's been used. Something like:

try:
    useData(sensitiveString)
except:
    print("There was a problem executing useData()")
finally:
    scrubFromMemory(sensitiveString) 

This is to minimize the chance of sensitiveString still inhabiting memory, even in the event of an error. I thought about altering the string, something like:

sensitiveString = "*" * (len(sensitiveString)-1)  # does this overwrites memory, or creates a new object?
sensitiveString = "*" * 10000  # sensitive string is guaranteed to be relatively short
del sensitiveString
gc.collect()

But I read somewhere that in python (due to c-implementation), modification of the string will result in creation of a new string object in memory. So the original sensitiveString can still "ghost" exist somewhere in the memory dump of the application. I'd like to avoid that. EDIT: typo - gc.collect() instead of just gc()

Any suggestions how I can completely scrub sensitiveString from memory?


Solution

  • Ok, apparently, there's no real way to do this in Python, since string objects are immutable. References to these strings exist all over the place. Best one can do, is del and gc.collect(). As specified in this link, "accept it, or move on. Anything else will give you a false sense of security"