简体   繁体   English

如何在密码学中生成相同的密钥

[英]How Can I Generate the same key in cryptography

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.我输入了一个字符串“something”,它每次都会生成一个键“some_key=”。

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!请帮助!

When use use a password-based key derivation function (KDF) like PBKDF2, scrypt, or Argon2, you need both a passphrase and a salt.当使用基于密码的密钥推导 function (KDF),如 PBKDF2、scrypt 或 Argon2,您需要密码和盐。 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.由于盐必须是唯一的但不是秘密的,您可以在加密数据前加上盐,然后在解密时将其剥离。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM