How to encrypt a python module asuming the decryption key is well hidden
Question: I have been seaching the internet for solutions of how to encrypt a python
script file and the answer is pretty much the same: "You can't". They all
refer to fact that the key will be exposed somehow.

I am developing a standalone electrical system, which uses the Raspberry Pi as
the main computer. All the python files are at the moment pretty much exposed
if someone steals the SD Card. Now I have a key stored in an external device
and Im using that to decrypt some text files. Now my question!

Is it possible to somehow encrypt vital part of my .py moduls content and
still be able to execute them using the external key, without exposing the
decrypted .py moduls on the SD Card? That is to protect the code, if someone
steals the SD Card and want to look what is on it. I know if someone steals
the integer system, it is a different story!

Hope some of you something about python module encryption.

Best Regards

Allan


Answer: While, as you mention, it's impossible to protect your python files from
_someone with logical access to the system_ (i.e.: someone who logs in as
`root`), it's easy and commonplace to protect against _physical theft_ of the
storage devices where they reside.

You can do it on at least three diferent levels:

  * Have a [encrypted filesystem](https://en.wikipedia.org/wiki/Disk_encryption) on the SD card, such as ext4 over [LUKS](https://en.wikipedia.org/wiki/Linux_Unified_Key_Setup), and have it mounted by Linux. [Here's a tutorial](http://realtechtalk.com/LUKScryptsetup_Tutorial_for_Linux_Hard_Drive_Partition_Encryption-1002-articles)
  * Keep a regular filesystem on the SD card, and use a [file-level encryption overlay](https://en.wikipedia.org/wiki/Filesystem-level_encryption) such as [encFS](https://en.wikipedia.org/wiki/EncFS)
  * Devise your own encryption scheme in python, possibly using `pycrypto`; decode the modules to strings and either write them in a ramdisk or `exec` the strings directly.

Personally, I'd go with the first option, for a couple of reasons:

  * It's transparent to your program, so you can be sure it'll keep working and there's no need for `__import__` or `exec` black magic.
  * It's potentially safer. Devising your own encryption scheme is frowned upon by the vast majority of IT security experts.
  * It'll make data recovery easier, in case you ever need it

Please note that all these protections are moot if the attacker has full
logical access to the system, **or** physical access to the place you store
the encryption keys.

