114. Data Encryption with cryptography

Below are 10 Python code snippets demonstrating how to perform data encryption and decryption using the cryptography library. This includes symmetric and asymmetric encryption, hashing, and key generation.


1. Generating a Symmetric Key

from cryptography.fernet import Fernet

# Generate a symmetric key
key = Fernet.generate_key()
print(f"Generated Key: {key.decode()}")

2. Encrypting and Decrypting Data with Symmetric Key

from cryptography.fernet import Fernet

# Generate and save the key
key = Fernet.generate_key()
cipher = Fernet(key)

# Encrypt data
data = b"Secret data"
encrypted_data = cipher.encrypt(data)
print(f"Encrypted: {encrypted_data}")

# Decrypt data
decrypted_data = cipher.decrypt(encrypted_data)
print(f"Decrypted: {decrypted_data.decode()}")

3. Saving and Loading a Key


4. Asymmetric Key Generation with RSA


5. Serializing RSA Keys


6. Encrypting Data with RSA


7. Decrypting Data with RSA


8. Hashing Data with SHA-256


9. Generating a Key Derivation Function (KDF)


10. Signing and Verifying Data with RSA


Summary:

These examples demonstrate how to perform:

  • Symmetric encryption with Fernet.

  • Asymmetric encryption with RSA.

  • Hashing with SHA-256.

  • Key derivation with PBKDF2.

  • Digital signature creation and verification.

Install the cryptography library with:

Let me know if you'd like further details on any of these techniques!

Last updated