Hướng dẫn python configparser encrypt password

I am using Python 3 I have an Auth_INI ConfigParser file with usernames mapped to passwords. I need to encrypt the password with the password so only the password can decrypt it.

> Auth_INI = ConfigParser()
> password = 'password'
> password_encrypted = encrypt(password,'password') 
> Auth_INI['username'] = password_encrypted

All it needs to be is somekind of difficult hash/unhash encoding perhaps. I do not require anything too fancy. No keyrings, just plain text encoded/unencoded.

With this encryption scheme I can easily verify a person by decrypt(password,'guessword') != 'guessword' and there is no reason to do anything more than this.

Is anyone able to recommend an encryption/Encoding library that works like this?

Right now I am just using urlsafe_b64encode('password') and there is no password to decode the password so essentially there is no encryption for the password. Please do help...

cryptoconfig

Python class for handling encrypted elements in a config file. Extension of ConfigParser.

This class overides the 'get' method of ConfigParser replacing it with Fernet symmetric encryption so that you can safely store encrypted passwords in an ini file.

Example ini file.

[PARSE_TEST]
user = dmartin
password = ba$1234!
password_encoded = enc(gAAAAABa7JOds0uLwiKb44pTUvLuzbcxLsmpWL7kCFYTKX0JTW6q_JLubSKFrecCF1ShsMvzEBnt16Da_LsgUN5ff5LwB6zwPw==)

Example code to parse the above ini example. Note: The encoded password is the same as the unencoded to demonstrate the use. Storing the crypt_key in the program should be discouraged. A better example would load the key from an environment variable.

from crypto_config import cryptoconfigparser
import os
import sys

if __name__ == "__main__":
    try:
        # CryptoConfigParser application encrypton string
        key = '-nBUOebi1SsnpU8k7lHym6oHSFN5Id3xM0Wezh8DHxg='

        properties = cryptoconfigparser.CryptoConfigParser(crypt_key=key)
        properties_file = os.path.dirname(__file__) + "/sample_parse.ini"
        properties.read(properties_file)
    
        user = properties.get('PARSE_TEST', 'user')
        password = properties.get('PARSE_TEST', 'password')
        password_encoded = properties.get('PARSE_TEST', 'password_encoded')
    except cryptoconfigparser.ParsingError as err:
        print('Could not parse:', err)
        sys.exit(1)

    print(f"user: {user} password: {password} decoded: {password_encoded}")

To install this from git use:

pip install git+https://github.com/NREL/CryptoConfig.git

This package installs a helper command line utility called cryptocfg.py to generate, encrypt, and decrypt Fernet password strings.

use: cryptocfg.py [options]
where options include:
	--decrypt= | -d, decrypt the string, requires -i and -p 
	--encrypt= | -e, encrypt the string, requires -i and -p 
	--input= | -i, string to encrypt or decrypt, if not supplied read from stdin
	--password= | -p, key for encrypting or decrypting a string, if not supplied will be prompted for
	--genkey generate an encryption/decryption string
examples:
Encrypt:
cryptocfg.py -i 'f00Baz!1234$' -p 'jsZ9EkC3_XnP88UwIGQdFWpKPpeaD61RqJy8DE6lLYk=' -e
Decrypt:
cryptocfg.py -i 'gAAAAABa8IpcHE03lpmYYhptWlkOqKMvstpbYlHqp9Asq5qVY024X7OhokVto2aF_uzCRP47OVdHT5VE6f32xIvvoMlDX3_Ceg==' -p 'jsZ9EkC3_XnP88UwIGQdFWpKPpeaD61RqJy8DE6lLYk=' -d

There is a right way to do this, but it's HARD.

You set up a centralized server for your master keystore that can only be brought up by hand -- someone has got to know a a pass phrase to bring the machine up, it's the only way to give strong encryption to on-disk secrets.

Fault tolerance is left as an exercise to the user.

Next, you invent a way for your server machines to get audited. You list a set of authorized machines in a database. When they come up, they connect to the key distribution center, and if they're authorized, you attempt to audit them (md5 of the kernel, scan for SUID binaries, what have you), and if the machine checks out, you give it the secret over a secure connection.

But you can only raise the bar with this sort of thing.

I haven't too often seen such a simple question that opens such a can of worms. Maybe a young child asking about god.

Password encryption masks users' passwords so they become hard to guess or decode. It's an essential step in developing secure user-base software. Whether you're building one with Flask or another light Python Framework, you can't ignore that step. That's where bcrypt comes in.

Nội dung chính

  • How bcrypt Works
  • Encrypting a Password in Python With bcrypt
  • Install and Set Up bcrypt
  • Start Encrypting Passwords
  • How to Compare and Confirm Passwords With bcrypt
  • Scale Up Encryption With bcrypt

Nội dung chính

  • How bcrypt Works
  • Encrypting a Password in Python With bcrypt
  • Install and Set Up bcrypt
  • Start Encrypting Passwords
  • How to Compare and Confirm Passwords With bcrypt
  • Scale Up Encryption With bcrypt

We'll show you how to use bcrypt to hash your password in Python.

How bcrypt Works

Bcrypt is a language-agnostic hashing library that offers unique password encryption. While encrypting your string, it generates extra random characters (salt) by default to beef up the security of your password.

Optionally, you can also specify the number of extra characters you want to add to an incoming string.

Thebcrypt library doesn't read raw strings—byte code only. So to start, you'll first encode an incoming password string before passing it to bcrypt for encrypting.

Encoding isn't the same as encrypting. It only ensures that a string becomes machine-readable before an encryption algorithm can mask it.

Encrypting a Password in Python With bcrypt

bcrypt password encryption is easy with Python. We'll focus on how to do this without using a framework. But no worries, it follows the same process in frameworks once you know how to store your users' inputs and read them from the database.

Install and Set Up bcrypt

If you haven't done so already, activate a Python virtual environment in your project root. Then install bcrypt using pip:

pip install bcrypt

Start Encrypting Passwords

Once installed, let's see how to encrypt a string using bcrypt:

import bcrypt  
password = "mypasswordstring"

# Encode password into a readable utf-8 byte code:
password = password.encode('utf-8')

# Hash the ecoded password and generate a salt:
hashedPassword = bcrypt.hashpw(password, bcrypt.gensalt())
print(hashedPassword)

When you run the Python code above, it prints an encrypted byte string. The output, however, changes each time you execute the script. This is how bcrypt ensures each user has a uniquely encrypted password.

That's for password encryption, by the way.

How to Compare and Confirm Passwords With bcrypt

What if you want to store the hashed password and confirm later that it matches a user's provided password during authentication?

That's easy. You only need to compare the authenticating password with the one stored in the database (or in memory in this case).

And since bcrypt only reads byte strings, you'll also need to encode the authenticating password before comparing it with the one in the database. In essence, you'll cross-check an encoded authentication input with the encoded hashed password already stored in your database.

Using dummy Python inputs, let's see how this works in practice:

import bcrypt

# store your password:
password = str(input("input password: "))

# Encode the stored password:
password = password.encode('utf-8')

# Encrypt the stored pasword:
hashed = bcrypt.hashpw(password, bcrypt.gensalt(10))

# Create an authenticating password input field to check if a user enters the correct password
check = str(input("check password: "))

# Encode the authenticating password as well
check = check.encode('utf-8')

# Use conditions to compare the authenticating password with the stored one:
if bcrypt.checkpw(check, hashed):
print("login success")
else:
print("incorrect password")

The above code asks you to input a new password when you execute it. Python stores this in memory. You'll then provide the same password (known only to you) in the authenticating field.

Python prints a success message if the compared password matches the previously stored encrypted one. Otherwise, it outputs the failed message wrapped in the else statement:

The whole concept is the same as storing a password in a database during registration and providing it later during authentication.

Scale Up Encryption With bcrypt

While we've only demonstrated how bcrypt works by storing encrypted passwords into plain Python short memory, its ultimate usage is in real-life user-base applications.

Nonetheless, this tutorial shows the fundamental ways to structure your code to achieve this, even in real-life scenarios. For instance, if you're using Flask, you can replace the inputs with separate web forms to serve the registration and authentication fields. And of course, you'll store encrypted passwords in a real-life database and read from it when comparing passwords.