Comment garantir un cryptage sécurisé en Python ?

DDD
Libérer: 2024-10-22 21:29:30
original
897 Les gens l'ont consulté

How to Ensure Secure Encryption in Python?

Cryptage sécurisé à l'aide d'une clé symétrique

L'approche recommandée pour le cryptage sécurisé en Python utilise la recette Fernet de la bibliothèque de cryptographie. Il utilise le cryptage AES CBC avec HMAC pour la vérification de l'intégrité, protégeant ainsi efficacement les données contre la falsification et le décryptage non autorisé.

Cryptage et décryptage Fernet

<code class="python">from cryptography.fernet import Fernet

# Generate a secret key for encryption
key = Fernet.generate_key()

# Encode a message (plaintext)
encoded_message = Fernet(key).encrypt(b"John Doe")

# Decode the encrypted message (ciphertext)
decoded_message = Fernet(key).decrypt(encoded_message)

print(decoded_message.decode())  # Output: John Doe</code>
Copier après la connexion

Clé Fernet dérivée d'un mot de passe

Bien qu'il soit recommandé d'utiliser une clé générée aléatoirement pour des raisons de sécurité, vous pouvez également dériver une clé à partir d'un mot de passe si nécessaire :

<code class="python">from cryptography.fernet import Fernet
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes

def derive_key(password):
    kdf = PBKDF2HMAC(
        algorithm=hashes.SHA256(),
        length=32,
        salt=secrets.token_bytes(16),
        iterations=100_000,
        backend=default_backend()
    )
    return b64e(kdf.derive(password.encode()))

# Generate a password using a key derivation function
key = derive_key(password)

# Encrypt and decrypt using the password-derived Fernet key
encoded_message = Fernet(key).encrypt(b"John Doe")
decoded_message = Fernet(key).decrypt(encoded_message)

print(decoded_message.decode())  # Output: John Doe</code>
Copier après la connexion

Obscurcissement des données

Pour les données non sensibles, pensez à utiliser base64 encodage au lieu du cryptage :

<code class="python">from base64 import urlsafe_b64encode as b64e

# Encode data
encoded_data = b64e(b"Hello world!")

# Decode data
decoded_data = b64d(encoded_data)

print(decoded_data)  # Output: b'Hello world!'</code>
Copier après la connexion

Signature des données

Signer les données pour garantir l'intégrité à l'aide de HMAC :

<code class="python">import hmac
import hashlib

# Sign data using a secret key
key = secrets.token_bytes(32)
signature = hmac.new(key, b"Data to sign", hashlib.sha256).digest()

# Verify the signature
def verify(data, signature, key):
    expected = hmac.new(key, data, hashlib.sha256).digest()
    return hmac.compare_digest(expected, signature)

# Verify the signature using the same key
print(verify(b"Data to sign", signature, key))  # Output: True</code>
Copier après la connexion

Autres : implémentations correctes de schémas non sécurisés

AES CFB :

<code class="python">import secrets
from base64 import urlsafe_b64encode as b64e, urlsafe_b64decode as b64d

from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend

backend = default_backend()

def aes_cfb_encrypt(message, key):
    algorithm = algorithms.AES(key)
    iv = secrets.token_bytes(algorithm.block_size // 8)
    cipher = Cipher(algorithm, modes.CFB(iv), backend=backend)
    encryptor = cipher.encryptor()
    return b64e(iv + encryptor.update(message) + encryptor.finalize())

def aes_cfb_decrypt(ciphertext, key):
    iv_ciphertext = b64d(ciphertext)
    algorithm = algorithms.AES(key)
    size = algorithm.block_size // 8
    iv, encrypted = iv_ciphertext[:size], iv_ciphertext[size:]
    cipher = Cipher(algorithm, modes.CFB(iv), backend=backend)
    decryptor = cipher.decryptor()
    return decryptor.update(encrypted) + decryptor.finalize()</code>
Copier après la connexion

AES ECB :

<code class="python">from base64 import urlsafe_b64encode as b64e, urlsafe_b64decode as b64d

from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.primitives import padding
from cryptography.hazmat.backends import default_backend

backend = default_backend()

def aes_ecb_encrypt(message, key):
    cipher = Cipher(algorithms.AES(key), modes.ECB(), backend=backend)
    encryptor = cipher.encryptor()
    padder = padding.PKCS7(cipher.algorithm.block_size).padder()
    padded_message = padder.update(message.encode()) + padder.finalize()
    return b64e(encryptor.update(padded_message) + encryptor.finalize())

def aes_ecb_decrypt(ciphertext, key):
    cipher = Cipher(algorithms.AES(key), modes.ECB(), backend=backend)
    decryptor = cipher.decryptor()
    unpadder = padding.PKCS7(cipher.algorithm.block_size).unpadder()
    padded_message = decryptor.update(b64d(ciphertext)) + decryptor.finalize()
    return unpadder.update(padded_message) + unpadder.finalize()</code>
Copier après la connexion

Remarque : AES ECB n'est pas recommandé pour un cryptage sécurisé.

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

source:php
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!