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

Copy

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

Copy

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

Copy


4. Asymmetric Key Generation with RSA

Copy


5. Serializing RSA Keys

Copy


6. Encrypting Data with RSA

Copy


7. Decrypting Data with RSA

Copy


8. Hashing Data with SHA-256

Copy


9. Generating a Key Derivation Function (KDF)

Copy


10. Signing and Verifying Data with RSA

Copy


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:

Copy

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

Last updated