1
在Python 3應用程序中,我需要使用自己的密碼來加密用戶的數據。 我正在使用Cryptodome庫。使用用戶密碼加密數據的AES加密示例類
鑑於AES需要一個固定大小的密鑰(在本例中爲128bit),我使用PBKDF2來獲得密鑰。 下面是我在我的代碼中使用的類。
予存儲用於密鑰推導,並在消息本身的頂部的初始化向量(在代碼IV)鹽(鹽中的代碼)。 事實上,對於我的理解(閱讀文檔here)鹽和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:])
在此先感謝。
是的,你是對的。 – decadenza