Reputation: 721
I need to use a password to sign in a service I need to do some stuff in Python, but I don't want to store the password in the code.
I did some research and found the base64 encode. This seems good, but it requires the password to be stored in the code anyway.
>>> import base64
>>> encoded = base64.b64encode('data to be encoded') # password stored in the code
>>> encoded
'ZGF0YSB0byBiZSBlbmNvZGVk'
>>> data = base64.b64decode(encoded)
>>> data
'data to be encoded'
For you guys who have already worked with password management in Python, what is the best option? Store the password in a file? Use only the b64encode()
string generated and decode it everythime the program needs the password?
Upvotes: 5
Views: 12232
Reputation: 30709
Don't embed the password (clear or obfuscated) in your program. Instead, allow the user to supply the password in a file. This is the approach taken by programs such as the standard FTP and MySQL clients.
For bonus points, check that the file cannot be read (and preferably not be written or replaced) by a different non-root user. If so, exit with an error message, so that the user must fix it.
Be aware that you will have a valuable password in memory - consider overwriting as soon as possible after use, so it's not present in any core file.
If your platform has a suitable keyring implementation, you might consider using the Python keyring package.
Upvotes: 3
Reputation: 113930
I can only assume you are talking about storing your credentials to a site, that the user is unable to register for themselves?
For a solution that avoids storing your credentials in the code you could create a middleware server that stores individual user credentials that users register for and then you store your site credentials on that server so that users hit an endpoint in your middleware that then does your query against the site using your login credentials and returns the output verbatim. however this is also a fairly difficult solution. however if you are distributing this to untrusted users and you think it is very important to protect the 3rd party credentials this is really the only choice you have.
another option is to allow users to directly register their own username/password with the 3rd party site (you might even be able to automate it) and then prompt the user for their unique credentials and store those in the users home directory or something (encrypt/encode if you want ...)
based on your edits I believe the following may apply to your use case If you are distributing it to a very small trusted group or you find a way to not care too much if people get the credentials out of the program there are many many ways to encode/encrypt/obfuscate your password in the code itself. including base64encoding it, or aes encrypting it, breaking it apart into several places. all of these will block the most common ways people scan code for passwords (but a determined person will definitely be able to recover it)
Upvotes: 7