简体   繁体   中英

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

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!!

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. :)

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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM