I have a program I'm writing in python, and I ha开发者_开发问答ve the need to store some passwords. These passwords will be the passwords to ftp servers, so it's important that they're not just plainly visible to everybody. This also means that I can't store a non-reversible hash of the password like you would on a webserver, because I'm not checking if somebody inputs the right password, I'm just relaying the password to somebody else.
So what's the best way to store passwords? I'm using python, and the program will be linux-only.You could use the system's key ring, e.g. GNOME key ring or KDE wallet.
There's a Python module called keyring that supports multiple key ring providers. I have only tried it on Windows, where it doesn't yet work correctly. Seems like development isn't very active, but you should give it a try. You can also try the package "python-gnomekeyring" which is specific to GNOME and more low-level.
Depending on the distribution you can probably store it in the keychain if one is available.
Otherwise take a look at some of the encryption algorithms available (PGP/GPG, DES, AES etc) and their Python ports/modules but this is hard stuff which you have to get right.
There's the convenient and insecure way: just store them as plaintext and if you are truly using FTP (and not, for example SFTP) then they will be as secure as the machine they are hosted upon (which means not really very secure). FTP was written in a time when sending a plaintext password over the wire was considered "safe enough"; those days are gone. Even encoding the plaintext passwords in the python source doesn't really help you as at some point you have to un-encode them.
Secure methods require a little more setup. Here is a decent tutorial, I expect there are better ones.
Check out netrc on Linux (use man or this) and then look at this Python module
If the netrc has the appropriate information you can use ftp at the command line without entering user and password - they are looked up in the file. Some things to note: the file has be restricted to user read/write only (0600) or it may be rejected by ftp. If that works, then you are ready to use it from Python.
A much better idea would be to avoid ftp altogether (where the password is sent in plain-text) and use sftp. Copy your public key from the machine running the Python script to each target machine and let ssh automatically login for you in a secure fashion.
I would recommend hashing the password a hash is a one way function so can't be worked back to find a plain text version of the password (unlike an encryption).
MD5 is a algorithm that I like and is already implemented in Python. You could always add a salt to the hash like abdPasswordABDA
where Password is the password. Then store the hash in a file or database and just hash it again before it gets checked. SHA1 is another hashing algorithm that you could use.
精彩评论