[python-crypto] Securely wiping cryptographic secrets in Python

desnacked at riseup.net desnacked at riseup.net
Sun Feb 3 17:59:41 CET 2013


>
> Hi,
>
> Le dimanche 03 février 2013 à 08:21 -0800, desnacked at riseup.net a
> écrit :
>> if I have a Python program that uses sensitive cryptographic material,
>> is
>> there a way to securely wipe them from memory after use?
>>
>> In C, this is usually done by (_carefully_) overwriting the array where
>> the secrets are stored. Is this possible to do in Python? I bet that if
>> I
>> try to overwrite a string in Python, there is absolutely no guarantee
>> that
>> the previous value of that string won't be copied somewhere else
>> beforehand. What happens if I use a lower level structure, like a
>> bytearray? Is that property of bytearrays guaranteed somewhere in the
>> Python spec?
>
> Python (or at least *CPython*, the reference implementation) doesn't
> copy data without you asking. However, you are right that neither does
> it try to securely wipe data after a memory block is deallocated.
>
> Without modifying Python, you could indeed use a bytearray and overwrite
> the bytearray's contents when you are done. Be careful to do it without
> changing the bytearray's size, otherwise the internal buffer might be
> reallocated and the old contents be left untouched somewhere in memory.
>
> Also, be aware that any conversion from bytes to bytearray, or from
> bytearray to bytes, will also copy data around. So will many other
> operations such as slicing. Therefore, if your cryptography is written
> in Python, chances are that parts of your data will be duplicated around
> at some point.
>

Thanks for the answer!

Hm, I see. That's approximately the answer I got from other Python-savvy
people too.

Is there a chance that the Python project could publish an article with
guidelines on how to treat bytearrays to _guarantee_ that no data leaking
will occur? It's reassuring to hear the above from you, but it would be
even better to have a paragraph on this matter on the Python
specification.

This way, applications using crypto and crypto libraries will know how to
setup their APIs and internal functions to allow cryptographic secret
wiping.




More information about the python-crypto mailing list