AES 加密示例 class 使用用户密码加密数据
AES encryption example class to encrypt data using user's password
在 Python 3 应用程序中,我需要使用用户自己的密码来加密用户数据。
我正在使用 Cryptodome 库。
鉴于AES需要固定大小的密钥(示例中为128位),我使用PBKDF2来获取密钥。
下面是我在代码中使用的 class。
我将用于密钥派生的盐(代码中的salt)和初始化向量(代码中的iv)存储在消息本身的顶部。
事实上,就我的理解(阅读文档 here)而言,salt 和 iv 都不必保密。
这是正确的方法吗?或者你能建议我更好的方法吗?
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:])
提前致谢。
是的,这是正确的,并且是向解密代码提供派生盐和 iv 的良好实践和好方法。
PBKDF 提供了针对暴力密码攻击的强大安全性以及正确长度的密钥。
在 Python 3 应用程序中,我需要使用用户自己的密码来加密用户数据。 我正在使用 Cryptodome 库。
鉴于AES需要固定大小的密钥(示例中为128位),我使用PBKDF2来获取密钥。 下面是我在代码中使用的 class。
我将用于密钥派生的盐(代码中的salt)和初始化向量(代码中的iv)存储在消息本身的顶部。 事实上,就我的理解(阅读文档 here)而言,salt 和 iv 都不必保密。
这是正确的方法吗?或者你能建议我更好的方法吗?
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:])
提前致谢。
是的,这是正确的,并且是向解密代码提供派生盐和 iv 的良好实践和好方法。
PBKDF 提供了针对暴力密码攻击的强大安全性以及正确长度的密钥。