Encryption (not hashing) of credentials in a Python connection string

I would like to know how to encrypt a database connection string in Python – ideally Python 3 – and store it in a secure wallet. I am happy to use something from pip. Since the connection string needs to be passed to the database connection code verbatim, no hashing is possible. This is motivated by:

  • a desire to avoid hard-coding the database connection credentials in a Python source file (bad for security and configurability);
  • avoid leaving them plain-text in a configuration file (not much better due to security concerns).

In a different universe, I have seen an equivalent procedure done in .NET using built-in machineKey / EncryptedData set up by aspnet_regiis -pe, but that is not portable.

Though this problem arises from an example where an OP is connecting via pymysql to a MySQL database,

  • the current question is specific neither to pymysql nor MySql, and
  • the content from that example is not applicable as a minimum reproducible example here.

The minimum reproducible example is literally

#!/usr/bin/env python3  PASSWORD='foo' 

Searching for this on the internet is difficult because the results I get are about storing user passwords in a database, not storing connection passwords to a database in a separate wallet.

I would like to do better than a filesystem approach that relies on the user account of the service being the only user authorized to view what is otherwise a plain-text configuration file.

Related questions

  • Securing connection credentials on a web server – but that requires manual intervention on every service start, which I want to avoid
  • Security while connecting to a MySQL database using PDO – which is PHP-specific and does not discuss encryption