Implementarea criptării și decriptării simetrice în Python

Configurare noua (How To)

Situatie

Solutie

Pasul 1: Instalarea Bibliotecii cryptography

Asigurați-vă că aveți instalată biblioteca cryptography în mediu:

pip install cryptography

Pasul 2: Implementarea Criptării și Decriptării

Implementați funcții pentru criptarea și decriptarea datelor folosind algoritmul AES în modul GCM (Galois/Counter Mode):

from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.primitives.asymmetric import rsa

def encrypt_data(data, password):
   salt = b’\xd1\x1e\x08I\x98w\xcf\xd7\x9b\xf4F<\xd5\xf0′
   kdf = PBKDF2HMAC(
      algorithm=hashes.SHA256(),
    length=32,
    salt=salt,
    iterations=100000,
    backend=default_backend()
  )
   key = kdf.derive(password)
   cipher = Cipher(algorithms.AES(key), modes.GCM(iv), backend=default_backend())
   encryptor = cipher.encryptor()
   ciphertext = encryptor.update(data) + encryptor.finalize()
   return ciphertext

def decrypt_data(ciphertext, password):
   salt = b’\xd1\x1e\x08I\x98w\xcf\xd7\x9b\xf4F<\xd5\xf0′
   kdf = PBKDF2HMAC(
     algorithm=hashes.SHA256(),
     length=32,
     salt=salt,
     iterations=100000,
     backend=default_backend()
   )
   key = kdf.derive(password)
   cipher = Cipher(algorithms.AES(key), modes.GCM(iv), backend=default_backend())
   decryptor = cipher.decryptor()
   plaintext = decryptor.update(ciphertext) + decryptor.finalize()
   return plaintext

Pasul 3: Testarea Criptării și Decriptării

Testați funcțiile de criptare și decriptare folosind datele dvs. și asigurați-vă că funcționează corect.

Tip solutie

Permanent

Voteaza

(1 din 4 persoane apreciaza acest articol)

Despre Autor

Leave A Comment?