0
0
PythonHow-ToBeginner · 3 min read

How to Encrypt String in Python: Simple Guide with Examples

To encrypt a string in Python, use the cryptography library's Fernet class which provides symmetric encryption. Generate a key with Fernet.generate_key(), create a Fernet object, then call encrypt() on your string encoded as bytes.
📐

Syntax

Here is the basic syntax to encrypt a string using the cryptography library's Fernet class:

  • key = Fernet.generate_key(): Generates a secure encryption key.
  • cipher = Fernet(key): Creates a cipher object using the key.
  • encrypted = cipher.encrypt(data): Encrypts the data (must be bytes).

Remember to convert your string to bytes using string.encode() before encrypting.

python
from cryptography.fernet import Fernet

key = Fernet.generate_key()
cipher = Fernet(key)

text = "Hello, world!"
encrypted = cipher.encrypt(text.encode())
💻

Example

This example shows how to encrypt and then decrypt a string using Fernet. It prints the encrypted bytes and the original text after decryption.

python
from cryptography.fernet import Fernet

# Generate a key and create a cipher
key = Fernet.generate_key()
cipher = Fernet(key)

# Original string
text = "Secret message"

# Encrypt the string (convert to bytes first)
encrypted = cipher.encrypt(text.encode())

# Decrypt back to original string
decrypted = cipher.decrypt(encrypted).decode()

print("Encrypted:", encrypted)
print("Decrypted:", decrypted)
Output
Encrypted: b'gAAAAABlYF0k...' Decrypted: Secret message
⚠️

Common Pitfalls

Common mistakes when encrypting strings in Python include:

  • Not converting the string to bytes before encryption, which causes errors.
  • Using the wrong key or losing the key, making decryption impossible.
  • Trying to encrypt without installing the cryptography library.

Always keep your key safe and never share it publicly.

python
from cryptography.fernet import Fernet

# Wrong: encrypting string directly causes error
# cipher = Fernet(Fernet.generate_key())
# encrypted = cipher.encrypt("text")  # This will raise TypeError

# Right way:
cipher = Fernet(Fernet.generate_key())
encrypted = cipher.encrypt("text".encode())
📊

Quick Reference

Remember these quick tips when encrypting strings in Python:

  • Use Fernet.generate_key() to create a secure key.
  • Always convert strings to bytes with .encode() before encrypting.
  • Use cipher.decrypt() and .decode() to get back the original string.
  • Keep your encryption key secret and safe.

Key Takeaways

Use the cryptography library's Fernet class for easy and secure string encryption.
Always convert strings to bytes before encrypting with .encode().
Keep your encryption key safe to be able to decrypt later.
Decrypt encrypted data with cipher.decrypt() and convert bytes back to string with .decode().