Hiding a password in a python script (insecure obfuscation only)

I have got a python script which is creating an ODBC connection. The ODBC connection is generated with a connection string. In this connection string I have to include the username and password for this connection.

Is there an easy way to obscure this password in the file (just that nobody can read the password when I'm editing the file) ?


Solution 1:

Base64 encoding is in the standard library and will do to stop shoulder surfers:

>>> import base64
>>>  print(base64.b64encode("password".encode("utf-8")))
cGFzc3dvcmQ=
>>> print(base64.b64decode("cGFzc3dvcmQ=").decode("utf-8"))
password

Solution 2:

Here is a simple method:

  1. Create a python module - let's call it peekaboo.py.
  2. In peekaboo.py, include both the password and any code needing that password
  3. Create a compiled version - peekaboo.pyc - by importing this module (via python commandline, etc...).
  4. Now, delete peekaboo.py.
  5. You can now happily import peekaboo relying only on peekaboo.pyc. Since peekaboo.pyc is byte compiled it is not readable to the casual user.

This should be a bit more secure than base64 decoding - although it is vulnerable to a py_to_pyc decompiler.

Solution 3:

Douglas F Shearer's is the generally approved solution in Unix when you need to specify a password for a remote login.
You add a --password-from-file option to specify the path and read plaintext from a file.
The file can then be in the user's own area protected by the operating system. It also allows different users to automatically pick up their own own file.

For passwords that the user of the script isn't allowed to know - you can run the script with elavated permission and have the password file owned by that root/admin user.