Python Encryption Guide: Base64, MD5, SHA1, HMAC, DES, AES, RSA
This article introduces common encryption methods—including Base64, MD5, SHA‑1, HMAC, DES, AES, and RSA—explains their principles, and provides complete Python code examples for encoding, decoding, and key handling, enabling readers to implement secure data transformations in their own projects.
In the era of information security, encrypting sensitive data during network transmission is essential. This article presents Python implementations of several widely used encryption algorithms.
Base64 Encryption
Base64 is a simple encoding method that does not require a key. It is often used as an outer wrapper for other encryption schemes.
import base64
# string to encrypt
str_encrypt = 'hello!'
# encrypt
base64_encrypt = base64.b64encode(str_encrypt.encode())
base64_encrypt_str = base64_encrypt.decode()
print("BASE64 encrypted:", base64_encrypt_str, type(base64_encrypt_str))
# decrypt
base64_decrypt = base64_encrypt_str.encode()
str_decrypt = base64.b64decode(base64_decrypt).decode()
print("BASE64 decrypted:", str_decrypt, type(str_decrypt))MD5 Encryption
MD5 produces a 128‑bit hash value and is commonly used for data integrity verification. It is a one‑way function and does not require decryption.
import hashlib
str_encrypt = "hello!"
hash_obj = hashlib.md5(str_encrypt.encode())
hash_obj.update(str_encrypt.encode("utf8"))
value = hash_obj.digest()
print("Binary string", repr(value))
print("Hex string", hash_obj.hexdigest())SHA‑1 Encryption
SHA‑1 generates a 160‑bit hash and is stronger than MD5. It is also a one‑way function used for digital signatures.
import hashlib
str_encrypt = "hello!"
hash_obj = hashlib.sha1(str_encrypt.encode())
hash_obj.update(str_encrypt.encode("utf8"))
value = hash_obj.hexdigest()
print("Hex string", value)HMAC Encryption
HMAC combines a hash function with a secret key to provide message authentication.
import hmac
import hashlib
str_encrypt = "hello!"
key = "abc"
mac = hmac.new(key.encode(encoding="utf-8"), str_encrypt.encode("utf8"), hashlib.md5)
value = mac.hexdigest()
print("Hex string", value)DES Encryption
DES is a symmetric block cipher that uses a 56‑bit key. The example shows encryption and decryption using the pyDes library.
import binascii
from pyDes import des, CBC, PAD_PKCS5
def des_encrypt(secret_key, s):
iv = secret_key
k = des(secret_key, CBC, iv, pad=None, padmode=PAD_PKCS5)
en = k.encrypt(s, padmode=PAD_PKCS5)
return binascii.b2a_hex(en)
def des_decrypt(secret_key, s):
iv = secret_key
k = des(secret_key, CBC, iv, pad=None, padmode=PAD_PKCS5)
de = k.decrypt(binascii.a2b_hex(s), padmode=PAD_PKCS5)
return de
secret_str = des_encrypt('12345678', 'hello!')
print(secret_str)
clear_str = des_decrypt('12345678', secret_str)
print(clear_str)AES Encryption – ECB Mode
AES is a modern symmetric block cipher. The ECB example demonstrates encryption without an initialization vector.
import base64
from Crypto.Cipher import AES
def add_to_16(s):
while len(s) % 16 != 0:
s += '\0'
return str.encode(s)
key = 'abc4567890abc458'
text = 'hello'
aes = AES.new(add_to_16(key), AES.MODE_ECB)
encrypted_text = str(base64.encodebytes(aes.encrypt(add_to_16(text))), encoding='utf8').replace('
', '')
decrypted_text = aes.decrypt(base64.decodebytes(bytes(encrypted_text, encoding='utf8'))).rstrip(b'\0').decode('utf8')
print('Encrypted:', encrypted_text)
print('Decrypted:', decrypted_text)AES Encryption – CBC Mode
CBC mode uses an initialization vector (IV) to make each block dependent on the previous one, improving security.
import base64
from Crypto.Cipher import AES
AES_SECRET_KEY = 'helloBrook2abcde'
IV = 'helloBrook2abcde'
BS = len(AES_SECRET_KEY)
pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS)
unpad = lambda s: s[0:-ord(s[-1:])]
def cryptoEn(string, key, iv):
mode = AES.MODE_CBC
cipher = AES.new(key.encode('utf8'), mode, iv.encode('utf8'))
encrypted = cipher.encrypt(bytes(pad(string), encoding='utf8'))
return base64.b64encode(encrypted).decode('utf-8')
def cryptoDe(destring, key, iv):
mode = AES.MODE_CBC
decode = base64.b64decode(destring)
cipher = AES.new(key.encode('utf8'), mode, iv.encode('utf8'))
decrypted = cipher.decrypt(decode)
return unpad(decrypted).decode('utf-8')
secret_str = cryptoEn('hello', AES_SECRET_KEY, IV)
print(secret_str)
clear_str = cryptoDe(secret_str.encode('utf8'), AES_SECRET_KEY, IV)
print(clear_str)RSA Encryption
RSA is an asymmetric encryption algorithm that uses a public key for encryption and a private key for decryption. It is widely used in secure communications and digital signatures.
Implementations can be found in libraries such as pycryptodome or cryptography, where a key pair is generated and used for encrypting and decrypting data.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Python Crawling & Data Mining
Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
