How to encrypt password with Python

Asked

Viewed 4,801 times

0

I need to encrypt password using Python, from what I saw in examples in PHP, they use a "module" that encrypts the password and which in theory does not decrypt, to validate the password they encrypt the password that the user typed and compare with the one that is encrypted in the database.

How to do this in Python? From what I could find on/tested, every time I put it to encrypt the result and always different, so how do I compare it? What I need to learn?

Fictional example of what’s happening to me:

First Attempt:

msg = "1234"
encript(msg) >> adsadasfafsa

Second Attempt:

msg = "1234"
encript(msg) >> weqwrewerwer

Concluding every time I encrypt the result is different, so I can’t compare.

1 answer

2

First, we need to install the bcrypt module, because it does not come by default. For this, just type the following command in the terminal:

sudo pip install bcrypt

Now we just use the module. I will post an example of use.

import bcrypt

senha = '12345'
salt = bcrypt.gensalt(8)

print salt
$2a$08$K02Yy9Sn2mDReCeHwu3zse

hash = bcrypt.hashpw(senha, salt)

print hash
$2a$08$K02Yy9Sn2mDReCeHwu3zseMpikne058OpGqfMhKHhuDLIYrnvNT9G

Source: blog pythoneiro - How to use bcrypt in python?

  • 1

    Can you explain a little better what each thing does? what gets stored in the salt, would be the key?

  • Junior, basically salt is storing the complexity that Voce will use in its encryption. When using the Voce HASHPW command you are encrypting your password with the selected complexity (salt), Voce can pass this value directly to the function. would look: hash = bcrypt.hashpw(password, bcrypt.gensalt(8))

  • Putting this in a Registration/Login password, when the user enters his password at the time of registration, I encrypt it with determining SALT and saved from db, and SALT needs to be saved in the case; for when the User is going to login and I compare what he typed with the password that is encrypted in db, correct?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.