Python – Using a bytearray rather than a string to store password in memory

python

Using a bytearray datatype to store a password (in memory) has an advantage over using a string datatype for a password in that a bytearray is mutable and can be overwritten with 0x00 values when the password is no longer needed for processing and until the password variable is garbage collected. It's not clear to me, however, whether overwriting 0x00 values will achieve what is intended. When a password is no longer needed, it should be wiped from memory, prior to GC. Is this possible in python 3.4 using bytearray?

Best Answer

At least using CPython, overwriting a bytearray is the way forward. Like most systems, CPython does not clear memory prior to garbage collection, so a manual erase is required. It also does not make copies of data unless specifically requested.

Be wary of other Python implementations, however. They often differ in specifics of how memory is managed and may, for example, use either a copying or compacting garbage collector. In such a case, manually erasing the password may not be enough, as the garbage collector may have moved the object reference, leaving behind a copy of the array's contents at the old location.

Related Topic