Python Encryption Algorithm Practice: Protect Your Data Security
Hello everyone, today we are going to talk about encryption algorithms in Python. In this data-driven era, protecting sensitive information has become increasingly important. Whether it’s protecting user passwords or encrypting important files, mastering some basic encryption techniques is very useful. So, let’s explore the secrets of implementing encryption in Python!
What is Encryption?
In simple terms, encryption is the process of converting plaintext information into ciphertext that is difficult to understand, and only those who possess the correct key can restore it. It’s like locking your secret diary – only you know where the key is!
Symmetric Encryption: AES Algorithm
Let’s first look at one of the most commonly used symmetric encryption algorithms – AES (Advanced Encryption Standard). Symmetric encryption uses the same key for both encryption and decryption, just like using the same key to lock and unlock a door.
We need to install the pycryptodome
library:
pip install pycryptodome
Here is a simple example of using AES to encrypt a string:
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
from Crypto.Util.Padding import pad, unpad
import base64
def encrypt_message(message, key):
cipher = AES.new(key, AES.MODE_CBC)
ct_bytes = cipher.encrypt(pad(message.encode('utf-8'), AES.block_size))
iv = base64.b64encode(cipher.iv).decode('utf-8')
ct = base64.b64encode(ct_bytes).decode('utf-8')
return iv + ct
def decrypt_message(encrypted_message, key):
iv = base64.b64decode(encrypted_message[:24])
ct = base64.b64decode(encrypted_message[24:])
cipher = AES.new(key, AES.MODE_CBC, iv)
pt = unpad(cipher.decrypt(ct), AES.block_size)
return pt.decode('utf-8')
# Generate a random 16-byte key
key = get_random_bytes(16)
message = "This is a secret message!"
encrypted = encrypt_message(message, key)
decrypted = decrypt_message(encrypted, key)
print(f"Original message: {message}")
print(f"Encrypted: {encrypted}")
print(f"Decrypted: {decrypted}")
When you run this code, you will see that the original message is encrypted into a seemingly random string of characters, and then successfully decrypted back.
Tip: In practical applications, ensure the secure storage of the key. Leaking the key equals leaking all encrypted information!
Asymmetric Encryption: RSA Algorithm
Next, let’s look at asymmetric encryption. Unlike symmetric encryption, asymmetric encryption uses a pair of keys: a public key and a private key. The public key can be shared openly for encryption, while the private key must be kept secret for decryption. It’s like a magical box that can only be used to put things in, but not take them out – only the owner of the box (the person with the private key) can open it!
Let’s implement it using the RSA algorithm:
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
import binascii
# Generate RSA key pair
key = RSA.generate(2048)
private_key = key.export_key()
public_key = key.publickey().export_key()
# Encrypt
message = b'Information that needs to be encrypted'
rsa_public_key = RSA.import_key(public_key)
rsa_public_key = PKCS1_OAEP.new(rsa_public_key)
encrypted = rsa_public_key.encrypt(message)
print(f"Encrypted: {binascii.hexlify(encrypted)}")
# Decrypt
rsa_private_key = RSA.import_key(private_key)
rsa_private_key = PKCS1_OAEP.new(rsa_private_key)
decrypted = rsa_private_key.decrypt(encrypted)
print(f"Decrypted: {decrypted}")
In this example, we first generated a pair of RSA keys, then used the public key to encrypt the information, and finally used the private key to decrypt it. This method is particularly suitable for scenarios where sensitive information needs to be transmitted over insecure channels.
Note: The length of the information encrypted with RSA cannot exceed the key length minus some padding length. For long messages, the usual practice is to use RSA to encrypt a symmetric key, and then use that symmetric key to encrypt the actual message.
Hash Functions: Irreversible “Encryption”
Let’s take a look at hash functions. Strictly speaking, hashing is not encryption because it is irreversible. However, it is very useful in protecting passwords and similar scenarios.
import hashlib
def hash_password(password):
# Using SHA-256 algorithm
return hashlib.sha256(password.encode()).hexdigest()
password = "my_secret_password"
hashed = hash_password(password)
print(f"Original password: {password}")
print(f"Hashed: {hashed}")
# Verify password
input_password = "my_secret_password"
if hash_password(input_password) == hashed:
print("Password correct!")
else:
print("Password incorrect!")
The characteristics of hash functions are:
-
The same input always produces the same output
-
The output length is fixed
-
It is impossible to deduce the input from the output
This is why many websites store the hash of your password instead of the actual password. Even if the database is breached, hackers cannot directly obtain the original password.
Tip: In practical applications, we usually “salt” the password before hashing to defend against rainbow table attacks.
Conclusion
Today, we learned about three common encryption methods:
-
Symmetric Encryption (AES)
-
Asymmetric Encryption (RSA)
-
Hash Functions (SHA-256)
Each method has its applicable scenarios. Symmetric encryption is fast and suitable for large amounts of data; asymmetric encryption has high security, suitable for key exchange; hash functions are suitable for password storage and data integrity verification.
Friends, that’s it for today’s Python learning journey! Remember to code along, and feel free to ask me any questions in the comments. Wishing everyone a pleasant learning experience and continuous improvement in Python!
Creating is not easy, please give a thumbs up before you go!
Like