0
0
PythonHow-ToBeginner · 3 min read

How to Decrypt String in Python: Simple Guide with Example

To decrypt a string in Python, use the cryptography library's Fernet class which provides symmetric encryption and decryption. First, generate or load a key, then use Fernet(key).decrypt(encrypted_string) to get the original text back.
📐

Syntax

Here is the basic syntax to decrypt a string using cryptography.fernet.Fernet:

  • key: A secret key used for both encryption and decryption.
  • Fernet(key): Creates a Fernet object with the key.
  • decrypt(token): Method to decrypt the encrypted string (token).
python
from cryptography.fernet import Fernet

key = b'your-secret-key'
fernet = Fernet(key)
decrypted = fernet.decrypt(encrypted_string)
💻

Example

This example shows how to generate a key, encrypt a message, and then decrypt it back to the original string.

python
from cryptography.fernet import Fernet

# Generate a key and save it
key = Fernet.generate_key()
fernet = Fernet(key)

# Original message
message = "Hello, friend!"

# Encrypt the message
encrypted = fernet.encrypt(message.encode())
print("Encrypted:", encrypted)

# Decrypt the message
decrypted = fernet.decrypt(encrypted).decode()
print("Decrypted:", decrypted)
Output
Encrypted: b'gAAAAABlYF7v...' Decrypted: Hello, friend!
⚠️

Common Pitfalls

Common mistakes when decrypting strings include:

  • Using a different key for decryption than the one used for encryption.
  • Trying to decrypt data that was not encrypted with Fernet.
  • Passing a string instead of bytes to the decrypt method.
  • Not handling exceptions like InvalidToken which occur if decryption fails.
python
from cryptography.fernet import Fernet, InvalidToken

key = Fernet.generate_key()
fernet = Fernet(key)

encrypted = fernet.encrypt(b"secret")

try:
    # Wrong key example
    wrong_fernet = Fernet(Fernet.generate_key())
    wrong_fernet.decrypt(encrypted)
except InvalidToken:
    print("Decryption failed: Invalid key or corrupted data")
Output
Decryption failed: Invalid key or corrupted data
📊

Quick Reference

Remember these key points when decrypting strings in Python:

  • Use the same key for encryption and decryption.
  • Always handle exceptions to catch decryption errors.
  • Encrypt and decrypt bytes, not plain strings.
  • Use cryptography library for secure symmetric encryption.

Key Takeaways

Use the same secret key for both encryption and decryption with Fernet.
Decrypt bytes, not plain strings, using Fernet's decrypt method.
Handle exceptions like InvalidToken to catch decryption errors.
The cryptography library provides secure and easy-to-use encryption tools.
Always keep your encryption key safe and never expose it publicly.