Home > other >  Passwords are not being encrypted in MYSQL
Passwords are not being encrypted in MYSQL

Time:07-07

I am currently trying to use bcrypt to encrypt/hash my passwords from my seeds and store them in MYSQL but it keeps giving me the same password. I am using python. Any help would be appreciated!

User.py

from app.db import Base
from sqlalchemy.orm import validates
from sqlalchemy import Column, Integer, String
salt = bcrypt.gensalt()


class User(Base):
  __tablename__ = 'users'
  id = Column(Integer, primary_key=True)
  username = Column(String(50), nullable=False)
  email = Column(String(50), nullable=False, unique=True)
  password = Column(String(200), nullable=False)

  @validates('email')
  def validate_email(self, key, email):
    # make sure email address contains @ character
    assert '@' in email

    return email


@validates('password')
def validate_password(self, key, password):
  assert len(password) > 4

  # encrypt password
  return bcrypt.hashpw(password.encode('utf-8'), salt)

seeds.py

from app.models import User
from app.db import Session, Base, engine

# drop and rebuild tables
Base.metadata.drop_all(engine)
Base.metadata.create_all(engine)

db = Session()

# insert users
db.add_all([
  User(username='alesmonde0', email='[email protected]', password='password123'),
  User(username='jwilloughway1', email='[email protected]', password='password123'),
  User(username='iboddam2', email='[email protected]', password='password123'),
  User(username='dstanmer3', email='[email protected]', password='password123'),
  User(username='djiri4', email='[email protected]', password='password123')
])

db.commit()

db.close()

CodePudding user response:

Assuming that:

  • you have copied the code exactly as in your original file
  • and that the “keeps giving me the same password” means that in database the open text password gets saved and not the hash from validators

If both above is correct, the issue is with the identation, i.e. the “validate_password” method is not in the User class at all. Try to ident it properly, it should trigger and hash the password.

CodePudding user response:

it keeps giving me the same password

You pass the same password and salt every single time:

>>> salt = bcrypt.gensalt()
>>> bcrypt.hashpw('password123'.encode('utf-8'), salt)
b'$2b$12$L14/6UZsC4YymGUiQgBxCO5c6YoHEFDSM9ZSvBW0CgO9YkRUGkXwW'
>>> bcrypt.hashpw('password123'.encode('utf-8'), salt)
b'$2b$12$L14/6UZsC4YymGUiQgBxCO5c6YoHEFDSM9ZSvBW0CgO9YkRUGkXwW'

If you want the same plaintext to result in different hashes using bcrypt, regenerate the salt each time you generate a hash (as you should be per best practice):

>>> bcrypt.hashpw('password123'.encode('utf-8'), bcrypt.gensalt())
b'$2b$12$e1.vrDabeTDcqjqJ3Wj1fuapoGBgRaTjYNEn.v1WvuBbQLIsNlS3O'
>>> bcrypt.hashpw('password123'.encode('utf-8'), bcrypt.gensalt())
b'$2b$12$jqE4jMUeGfTLYixrR5iB0OAWSM/ZIEPiscX5fPLcxn8rOHqzJOUt6'
  • Related