如何使用Django和pycrpytodome加密数据并将其存储到数据库中?

2024-04-16 13:30:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用django创建了一个数据库,并创建了一个html表单将数据存储到数据库中。 现在,我想用pycryptodome加密并将密文存储到数据库中。 当我显示数据库中的数据时,我需要解密的明文。你知道吗

我从pycrytodome文档中尝试了一些基本的加密示例和算法。 现在,我想加密密文并将其存储到数据库中。你知道吗

#This is the function where I want to encrypt the data in the get_password variable and store it
def add(request):
    get_name = request.POST["add_name"]
    get_password = request.POST["add_password"]
    print(type(get_name),type(get_password))
    s = Student(student_name=get_name,student_password=get_password)
    context = { "astudent":s }
    s.save()
    return render(request,"sms_2/add.html",context)
#This is the example I have tried from pycryptodome documentation.
from Crypto.Cipher import AES
key=b"Sixteen byte key"
cipher=AES.new(key,AES.MODE_EAX)
data=b"This is a secret@@!!"
nonce = cipher.nonce
ciphertext, tag = cipher.encrypt_and_digest(data)
print(nonce)
print(key)
print(cipher)
print(ciphertext)
print(tag)




cipher1 = AES.new(key, AES.MODE_EAX, nonce=nonce)
plaintext = cipher1.decrypt(ciphertext)
try:
    cipher1.verify(tag)
    print("The message is authentic:", plaintext)
except ValueError:

    print("Key incorrect or message corrupted")

我想用html表单加密我输入数据库的明文,我想把密文存储到数据库中。 我需要帮助。你知道吗


Tags: thekeynameadd数据库getisrequest