【发布时间】:2017-08-08 08:36:17
【问题描述】:
在 Python 3 应用程序中,我需要使用用户自己的密码来加密用户的数据。 我正在使用 Cryptodome 库。
鉴于 AES 需要一个固定大小的密钥(示例中为 128 位),我使用 PBKDF2 来获取密钥。 下面是我在代码中使用的类。
我将用于密钥派生的盐(salt 在代码中)和初始化向量(在代码中的iv)存储在消息本身的顶部。 事实上,据我所知(阅读文档here),盐和静脉注射都不能保密。
这是一个正确的方法还是你能建议我一个更好的方法?
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
from Crypto.Protocol import KDF
class crypto:
def __init__(self,pwd):
self.pwd = pwd
def encrypt(self,data):
salt = get_random_bytes(8)
key = KDF.PBKDF2(self.pwd,salt) #128bit key derivation function
iv = get_random_bytes(16)
cipher = AES.new(key, AES.MODE_CFB, iv)
return salt + iv + cipher.encrypt(data)
def decrypt(self,msg):
key = KDF.PBKDF2(self.pwd,msg[:8])
cipher = AES.new(key, AES.MODE_CFB, msg[8:24])
return cipher.decrypt(msg[24:])
提前致谢。
【问题讨论】:
-
是的,你是对的。
标签: python-3.x aes encryption-symmetric