我目前正在嘗試使用 bcrypt 來加密/散列我的種子密碼並將它們儲存在 MYSQL 中,但它一直給我相同的密碼。我正在使用Python。任何幫助將不勝感激!
用戶.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)
種子.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='nwestnedge0@cbc.ca', password='password123'), User(username='jwilloughway1', email='rmebes1@sogou.com', password='password123'), User(username='iboddam2', email='cstoneman2@last.fm', password='password123'), User(username='dstanmer3', email='ihellier3@goo.ne.jp', password='password123'), User(username='djiri4', email='gmidgley4@weather.com', password='password123') ]) db.commit() db.close()
您每次都會傳遞相同的密碼和鹽:
如果您希望使用
bcrypt
相同的明文產生不同的雜湊值,請在每次產生雜湊值時重新產生鹽(按照最佳實踐,您應該這樣做):假設:
如果以上都正確,則問題出在驗證上,即「validate_password」方法根本不在 User 類別中。 嘗試正確識別它,它應該觸發並散列密碼。