0

I am trying to make an application that encodes and decodes a file for security.

What I am trying to achieve is this:

I entered a string 'something' and it will generate a key 'some_key=' everytime.

I tried out doing this:

import os
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
from cryptography.hazmat.backends import default_backend
from cryptography.fernet import Fernet

backend = default_backend()
salt = os.urandom(16)

kdf = PBKDF2HMAC(
    algorithm=hashes.SHA256(),
    length=32,
    salt=salt,
    iterations=100000,
    backend=backend
)
key = base64.urlsafe_b64encode(kdf.derive(b"my great password"))

f = Fernet(f)

But what i try to do, it is generating random keys.

I dont know what to do. Plz Help!

  • 3
    I'm afraid you must learn more about the "salt". It's purpose is what you trying to avoid, i.e. to generate different hashed passwords for the same input. – VPfB Jan 14 '21 at 10:16

1 Answers1

2

When use use a password-based key derivation function (KDF) like PBKDF2, scrypt, or Argon2, you need both a passphrase and a salt. The purpose of the salt is to make the use of the same passphrase produce different keys each time. Otherwise, everybody who used the same passphrase would derive the same key, which poses a lot of security problems.

That means that you need to store the salt with the file so that you can derive the same key. Since the salt must be unique but isn't secret, you can just prepend the encrypted data with the salt, and then strip it off when decrypting.

bk2204
  • 64,793
  • 6
  • 84
  • 100