3

I know that Python strings are immutable in the way they don't have write accessors, but assume I store a private key in memory. Is there a way I can clean de memory occupied by the string when I don't use it anymore? (clean means zero-filling). I don't expect the string classes have a method like this, but perhaps a python (perhaps a C extension) library does.

My problem: When a string memory space holding a private key is not used anymore, clean that space with zeroes (after losing all the references, it will be garbage collected eventually, but I want to ensure no remains of the PK is in memory when it happens).

Edit I am using PyCrypto with RSA, AES, PKCS 1.5.

Luis Masuelli
  • 12,079
  • 10
  • 49
  • 87
  • 4
    Depending on the string, you might be able to use a `bytearray` instead. `bytearray` have lots of the same methods that python byte-`str` have, but they're mutable so you can overwrite it with nulls if you so desire ... If you need non-ascii characters, this becomes significantly more cumbersome though ... – mgilson May 24 '16 at 18:11
  • Can I use a bytearray as a PyCrypto key? – Luis Masuelli May 24 '16 at 18:12
  • You could try `del key; key = "0"*512; key = "1"*128"; del key` – ForceBru May 24 '16 at 18:12
  • Try import sys sys.modules[__name of string__].__dict__.clear() – KrunalParmar May 24 '16 at 18:15
  • 1
    @ForceBru no. In standard cpython implementations, `id()` returns the memory address of the object. By assigning like you said, I have a different object later, but I don't have guarantee that the first was removed, and whether its blob memory was overwritten by another object. Try the code yourself, but calling `id(key)` before and after, and you will see the id return values are different. – Luis Masuelli May 24 '16 at 18:15
  • @LuisMasuelli, I know, but Python _may_ reuse the old memory location for new data if you assign to `key` immediately after you `del` it, though there are no guarantees that it does it. – ForceBru May 24 '16 at 18:17
  • 1
    Doing this right is surprisingly tricky, even in languages that give you much more control over memory. Do your best to delegate the task to whatever crypto library you're using. If your crypto library is not designed with this in mind, trying to do it yourself will only give you a false sense of security. – user2357112 May 24 '16 at 18:20
  • Can I use bytearray with pycrypto so that there is only one reference and no content copies? – Luis Masuelli May 24 '16 at 18:22
  • I mena: If PyCrypto copies the key somehow in an intermediate place, I am screwed regardless the trick. If PyCrypto uses only the source and makes no copies of it (and just keeps references to the original array), then perhaps I could clean it. bytearray was a suggestion from @mgilson I never though about. – Luis Masuelli May 24 '16 at 18:24

0 Answers0