4

is it secure for python use pickle file to store the username and password?

I try to figure out what is the good practice to store the username and password in python? Can I just use pickle file?

Thanks!!

Jenny B
  • 179
  • 1
  • 4
  • 8
  • That's only for persistence, not encryption. Anyone who gets access to that file can just start Python and unpickle it. – TigerhawkT3 Dec 10 '16 at 06:58

2 Answers2

3

No. It's not secure to store username and password in pickle file.

Because a pickle file created on one computer can easily be read on another computer. Anyone who gets access to the file will be able to un-pickle it using the same pickle program you have used to pickle it.

You should ideally encode passwords using salt and secret key. There are bcrypt libraries which do this.

Ideally you should not store passwords in files. Rather databases are a safer option. Also use standard libraries that automatically hash passwords using salts and store details in databases.

Make sure the database is password protected and system is secure using se-linux. What else?? Yeah, avoid storing passwords. Give google/Fb/Twitter login wherever possible. :)

Vikash Singh
  • 13,213
  • 8
  • 40
  • 70
3

Providing examples to Vikash's excellent answer below.

Secure Password Storage in Python:

import bcrypt
import hmac
from getpass import getpass
master_secret_key = getpass('tell me the master secret key you are going to use')    
# Calculating a hash
hashed = bcrypt.hashpw(password, bcrypt.gensalt())
# Validating a hash (don't use ==)
if (hmac.compare_digest(bcrypt.hashpw(password, hashed), hashed)):
    # Login successful

Now that have the salt and hashed password, you need to store it somewhere on disk. Where ever you do store it, you should set the file permissions to 600 (read/write by user only). If you plan on not allowing password changes, then 400 is better.

Here's how you can do that:

import os
import stat

# Define file params
fname = '/tmp/myfile'
flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL  # Refer to "man 2 open".
mode = stat.S_IRUSR | stat.S_IWUSR  # This is 0o600 in octal and 384 in decimal.

# For security, remove file with potentially elevated mode
try:
    os.remove(fname)
except OSError:
    pass

# Open file descriptor
umask_original = os.umask(0)
try:
    fdesc = os.open(fname, flags, mode)
finally:
    os.umask(umask_original)

# Open file handle and write to file
with os.fdopen(fdesc, 'w') as fout:
    fout.write('something\n')
Community
  • 1
  • 1
paragbaxi
  • 3,965
  • 8
  • 44
  • 58
  • 1
    What's going on in this code? `master_secret_key` is read but unused, `password` is hashed twice… https://stackoverflow.com/questions/12042724/securely-storing-passwords-for-use-in-python-script has the proper implementation, but even better just use a credential store https://stackoverflow.com/questions/7014953/i-need-to-securely-store-a-username-and-password-in-python-what-are-my-options – Clément Nov 03 '22 at 17:36