Heim  >  Fragen und Antworten  >  Hauptteil

Passwörter in MYSQL sind nicht verschlüsselt

Ich versuche derzeit, bcrypt zu verwenden, um meine Seed-Passwörter zu verschlüsseln/zu hashen und sie in MYSQL zu speichern, aber es gibt mir immer wieder das gleiche Passwort. Ich verwende Python. Jede Hilfe wäre sehr dankbar!

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)

seed.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()

P粉593536104P粉593536104236 Tage vor450

Antworte allen(2)Ich werde antworten

  • P粉710478990

    P粉7104789902024-03-20 16:34:19

    您每次都传递相同的密码和盐:

    >>> 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'

    如果您希望使用 bcrypt 相同的明文产生不同的哈希值,请在每次生成哈希值时重新生成盐(按照最佳实践,您应该这样做):

    >>> 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'

    Antwort
    0
  • P粉807239416

    P粉8072394162024-03-20 14:47:25

    假设:

    • 您已复制与原始文件中完全相同的代码
    • 并且“不断给我相同的密码”意味着在数据库中保存的是开放文本密码,而不是来自验证器的哈希

    如果以上都正确,则问题出在身份验证上,即“validate_password”方法根本不在 User 类中。 尝试正确识别它,它应该触发并散列密码。

    Antwort
    0
  • StornierenAntwort