Clearing (zeroing) all bytes of a sensitive bytearray in memory

74 Views Asked by At

After reading the following answer, I want to make sure a bytearray with sensitive information (password) is correctly cleared in memory prior to garbage collection. I'm assuming garbage collection in python only removes the pointer but does not replace the actual data with zeros in memory.

What is the correct way of doing this?

This is what I'm trying to do, but I don't know how to verify that it works as intended:

class CachedPasswordWidget(QtWidgets.QWidget):
    """A base class for widgets that may prompt the user for a  password and
    remember that password for the lifetime of that widget.
    """

    def __init__(
        self,
        parent: Optional[QtWidgets.QWidget] = None,
    ):
        super().__init__(parent)
        # store the password as a mutable type so the memory can be zeroed after it is no longer needed
        self._pwd: Optional[bytearray] = None

    @property
    def pwd(self) -> Optional[str]:
        """Return password.

        Open a dialog to ask for the wallet password if necessary, and cache it.
        If the password dialog is cancelled, return None.
        """
        if self._pwd is not None:
            return self._pwd.decode("utf-8")

        # password = PasswordDialog(parent=self).run()
        password = getpass.getpass()
        if password is None:
            # dialog cancelled
            return
                
        self._pwd = bytearray(password.encode("utf-8"))
        return self._pwd.decode("utf-8")

    def __del__(self):
        if self._pwd is not None:
            self._pwd[:] = b"\0" * len(self._pwd)

I guess what I'm asking is whether I can be sure that overwriting a slice of a bytearray will overwrite exactly the same memory as was used before, and whether I can be sure __del__ will be called in a timely manner by the garbage collector.

0

There are 0 best solutions below