Welcome to the Python Encryption/Decryption Tutorial! In this lesson, we'll dive into the fascinating world of data protection, where we'll learn how to convert plain text into an unreadable format (encryption) and back into readable text (decryption) using Python. ๐
Encryption is a fundamental aspect of modern communication and data security. It ensures the confidentiality, integrity, and authenticity of sensitive data. In this tutorial, we'll cover two common encryption techniques: Symmetric Encryption and Asymmetric Encryption.
Symmetric encryption uses the same key for both encryption and decryption. It's fast and efficient but requires the communicating parties to share the secret key securely.
Let's begin with a simple example: the Caesar Cipher. This ancient method shifts each letter in the plaintext by a certain number of positions.
def caesar_cipher(text, shift):
encrypted_text = ""
for char in text:
if char.isalpha():
ascii_offset = ord('a') if char.islower() else ord('A')
encrypted_text += chr((ord(char) - ascii_offset + shift) % 26 + ascii_offset)
else:
encrypted_text += char
return encrypted_text
plaintext = "Hello, World!"
shift = 3
print(caesar_cipher(plaintext, shift))๐ Note: Try changing the shift value to see how the ciphertext changes!
Asymmetric encryption uses two different keys: a public key for encryption and a private key for decryption. This allows for secure key exchange without requiring the keys to be sent through insecure channels.
RSA (RivestโShamirโAdleman) is a popular asymmetric encryption algorithm. Here's a simplified example of RSA encryption in Python using the pycryptodome library:
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
from Crypto.Random import get_random_bytes
def rsa_keys(bits=2048):
key = RSA.generate(bits, get_random_bytes)
public_key = key.publickey().exportKey()
private_key = key.exportKey()
return public_key, private_key
def rsa_encrypt(public_key, message):
cipher = PKCS1_OAEP.new(public_key)
encrypted_message = cipher.encrypt(message)
return encrypted_message
def rsa_decrypt(private_key, encrypted_message):
key = RSA.importKey(private_key)
cipher = PKCS1_OAEP.new(key)
decrypted_message = cipher.decrypt(encrypted_message)
return decrypted_message
public_key, private_key = rsa_keys()
message = "Hello, World!".encode()
encrypted_message = rsa_encrypt(public_key, message)
decrypted_message = rsa_decrypt(private_key, encrypted_message)
print(decrypted_message.decode())In symmetric encryption, what's the common name for the key used for both encryption and decryption?
In this tutorial, we've explored the fascinating world of encryption and decryption in Python. You learned about symmetric and asymmetric encryption, and even got a chance to try your hand at the Caesar Cipher and RSA encryption! Keep practicing, and soon you'll be able to protect your data like a pro! ๐ซ
Don't forget to check out other exciting Python tutorials on CodeYourCraft! Happy coding! ๐