0

I have used this code for encoding and decoding the user's password to save in the SQL database PostgreSQL using SQLAlchemy.

In the login process (using verify_password function), I will get ValueError: Invalid salt

import bcrypt


def encode_password(password: str) -> bytes:
    """
        Hashing the Password
    """
    return bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt())


def verify_password(password: str, hashed_password: str):
    """
        Decode the Password
    """
    return bcrypt.checkpw(password.encode("utf-8"), hashed_password.encode("utf-8"))

User Model

class User(Base):
    """
        User Model
    """
    __tablename__ = "users"

    id = Column(Integer, primary_key=True)
    mobile = Column(String, unique=True, nullable=False)
    email = Column(String, unique=True, nullable=False)
    password = Column(String, nullable=False)
AliAryaie
  • 107
  • 1
  • 8
  • `verify_password('abc', encode_password('abc').decode('utf-8'))` works for me. Maybe something goes wrong when translating the hash into a string? – jfschaefer Oct 17 '22 at 08:58
  • i will retrieve hashed password from database – AliAryaie Oct 17 '22 at 09:02
  • I can also recommend using a library like passlib: https://passlib.readthedocs.io/en/stable/ - to handle this for you, instead of having to implement it yourself, including support for migrating hashes as algorithms change. – MatsLindh Oct 17 '22 at 10:57
  • [Related](https://stackoverflow.com/q/34548846/5320906), if not a duplicate. – snakecharmerb Oct 17 '22 at 14:58

1 Answers1

0

I found the problem

in the saving process, we should decode hashed_password in order to save it into the database. Like this:

def create_user(db: Session, user: schemas.UserRegister):
    """
        Register A New User
    """
    hashed_password = encode_password(
        user.password
    )
    db_user = models.User(
        mobile=user.mobile,
        email=user.email,
        password=hashed_password.decode("utf-8")
    )
    db.add(db_user)
    db.commit()
    db.refresh(db_user)
    return db_user
AliAryaie
  • 107
  • 1
  • 8