0

I have a sensitive data field that I want to have as shortest life cycle as possible in memory. Following the post here I have the following implementation:

class UserData:
    def __init__(data):
        self.user_data = data #sensitive data 

    def get_user_data(self):
        return UserData.decrypt(self.user_data)

    @staticmethod
    def decrypt(data):
        ...

Following the post here, it seems the best I can do is to use del and make the string available for GC. I have the following implementation:

class UserData:
    def __init__(data):
        self.user_data = data #sensitive data 
        self._decrypted_user_data = None 

    @contextmanager      
    def get_user_data(self):
        self._decrypted_user_data = UserData.decrypt(self.user_data)
        yield
        del self._decrypted_user_data

    @staticmethod
    def decrypt(data):
        ...     

I have two questions:

Does the del on instance variable make the variable available for GC (i.e. is the reference count 0 on the instance variable). The reason I am asking is because I know dict returns the attributes. If not is there a way to mark the instance ready for GC instead of the whole object?

Is it safer than doing self._decrypted_user_data = None?

Community
  • 1
  • 1
as3rdaccount
  • 3,711
  • 12
  • 42
  • 62
  • What is the reasoning for making the data a property of the object, and having a del after yield? – Hamish Jun 05 '14 at 23:42

1 Answers1

2

del marks an object as garbage, but doesn't zap it.

In Python, strings are immutable. Even if you del a string, it'll exist in memory, although unretrievable. Considering using another type that is overwritable:

bytearray([source[, encoding[, errors]]])

Return a new array of bytes. The bytearray type is a mutable sequence of integers in the range 0 <= x < 256. It has most of the usual methods of mutable sequences, described in Mutable Sequence Types, as well as most methods that the bytes type has, see Bytes and Byte Array Methods.

https://docs.python.org/3.1/library/functions.html#bytearray

To store a password, read/write it as a bytearray, ie a string of numbers. To delete the password, overwrite the elements of the bytearray, then del the reference. Even if the object were to resurface, it would be filled with gibberish.

johntellsall
  • 14,394
  • 4
  • 46
  • 40
  • Thanks! The caller expects the password to be a string to pass into some web service call. I guess the caller could convert from byteaaray to string but then I will have the same problem. – as3rdaccount Jun 05 '14 at 23:50
  • To be honest I'd just use a string and `del` it, but the `bytearray` method seems like it would make paranoid security types happier. – johntellsall Jun 05 '14 at 23:52