Securely storing passwords for use in python script [duplicate] Securely storing passwords for use in python script [duplicate] python python

Securely storing passwords for use in python script [duplicate]


Know the master key yourself. Don't hard code it.

Use py-bcrypt (bcrypt), powerful hashing technique to generate a password yourself.

Basically you can do this (an idea...)

import bcryptfrom getpass import getpassmaster_secret_key = getpass('tell me the master secret key you are going to use')salt = bcrypt.gensalt()combo_password = raw_password + salt + master_secret_keyhashed_password = bcrypt.hashpw(combo_password, salt)

save salt and hashed password somewhere so whenever you need to use the password, you are reading the encrypted password, and test against the raw password you are entering again.

This is basically how login should work these days.


I typically have a secrets.py that is stored separately from my other python scripts and is not under version control. Then whenever required, you can do from secrets import <required_pwd_var>. This way you can rely on the operating systems in-built file security system without re-inventing your own.

Using Base64 encoding/decoding is also another way to obfuscate the password though not completely secure

More here - Hiding a password in a python script (insecure obfuscation only)


the secure way is encrypt your sensitive data by AES and the encryption key is derivation by password-based key derivation function (PBE), the master password used to encrypt/decrypt the encrypt key for AES.

master password -> secure key-> encrypt data by the key

You can use pbkdf2

from PBKDF2 import PBKDF2from Crypto.Cipher import AESimport ossalt = os.urandom(8)    # 64-bit saltkey = PBKDF2("This passphrase is a secret.", salt).read(32) # 256-bit keyiv = os.urandom(16)     # 128-bit IVcipher = AES.new(key, AES.MODE_CBC, iv)

make sure to store the salt/iv/passphrase , and decrypt using same salt/iv/passphase

Weblogic used similar approach to protect passwords in config files