Search code examples
pythonencryptionsqlalchemypython-cryptography

Encrypt personal data with a second hash from the password while already having a hash stored


The database looks like this:

class Users(UserMixin,db.Model):
    __tablename__ = "users"
    id = db.Column("id", db.Integer, primary_key=True)
    username = db.Column(db.String(100))
    hash_password = db.Column(db.Text)
    secret_content = db.Column(db.Text)

The secret content is highly confidential, I don't even want the admin to know the content of the data. My idea was to encode the content like this:

class Users(UserMixin,db.Model):
    __tablename__ = "users"
    id = db.Column("id", db.Integer, primary_key=True)
    username = db.Column(db.String(100))
    hash_password = db.Column(db.Text)
    secret_content = db.Column(db.Text)
    def __init__(self, username , password_hash, secret_content, key):
        cipher_suite = Fernet(key)
        self.username = username 
        self.secret_content = cipher_suite.encrypt(bytes(secret_content))
        self.hash_password = password_hash

The key used to encrypt the data should be different for each user. I wanted to create the key by hashing the password with sha256. However, the hash is already stored in the user for login purposes. Therefore I would use another hashing algorithm, MD5 for example.

The issue I see by doing that is that if a hacker is able to find/decypher this hash then he would be able to also extract the real password because at that point you can eliminate a lot of possibilities when the hacker brute forces the password.

Do I have other options or will I need to ask the user for a second unrelated password?


Solution

  • Based on the comments from @Artjom B.

    Add salt to the key. Encrypt key with PBKDF2 to encode the personal data with. Encrypt the same key with sh256 for user login.