Python函数如何实现简单加密和解密算法
发布时间:2023-06-20 22:33:06
Python中可以使用多种方式实现简单的加密和解密算法,例如对称加密、非对称加密、哈希函数等。下面将介绍一些实现方法。
对称加密
对称加密使用同一个密钥进行加密和解密,常见的对称加密算法有DES、AES等。
例如实现一个简单的AES加密和解密函数:
import base64
from Crypto.Cipher import AES
# 定义密钥和偏移向量
key = b'0123456789abcdef'
iv = b'1234567890abcdef'
# 加密函数
def encrypt(msg):
cipher = AES.new(key, AES.MODE_CBC, iv)
padded_msg = msg + (16 - len(msg) % 16) * b'\0'
ciphertext = cipher.encrypt(padded_msg)
return base64.b64encode(ciphertext)
# 解密函数
def decrypt(ciphertext):
cipher = AES.new(key, AES.MODE_CBC, iv)
padded_msg = cipher.decrypt(base64.b64decode(ciphertext))
return padded_msg.rstrip(b'\0')
使用方法:
msg = b'Hello, world!'
encrypted = encrypt(msg)
print('Encrypted:', encrypted)
decrypted = decrypt(encrypted)
print('Decrypted:', decrypted)
输出结果:
Encrypted: b'Ny/UB6rB6TqGTYufyUwJNQ==' Decrypted: b'Hello, world!'
非对称加密
非对称加密算法使用公钥和私钥进行加密和解密,常见的非对称加密算法有RSA、ECC等。
例如实现一个简单的RSA加密和解密函数:
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
# 生成公钥和私钥
key = RSA.generate(2048)
# 加密函数
def encrypt(msg):
cipher = PKCS1_OAEP.new(key.publickey())
ciphertext = cipher.encrypt(msg)
return ciphertext
# 解密函数
def decrypt(ciphertext):
cipher = PKCS1_OAEP.new(key)
padded_msg = cipher.decrypt(ciphertext)
return padded_msg
使用方法:
msg = b'Hello, world!'
encrypted = encrypt(msg)
print('Encrypted:', encrypted)
decrypted = decrypt(encrypted)
print('Decrypted:', decrypted)
输出结果:
Encrypted: b'\xd9\xb4E\x8b\xbbenE\xafQQE\x12A[f\xeaY\xdb\xf7\xd4\xb5\x8e\xb3<\xbc(\x8eV\xae\x1dh\x8d_\x8d\x9d\x82$d\xba;j6\x86U\xf2K\x0e\x0b1\xcb\x88N\xa1\x15&\xba\xf3\xb3>{\x1a\x8d\xed\x1fA\xb5i5\xdb\xbb\xed\x10p\x98\xacRY\x08\xcb}\xb1\x1e\xc7,\xd8\xde%}\xaa\x8c\xb9\xd8<\xdeA\xbd\xdf'\xd5\xf4CN<\xcd\x9e)fR\x06\xa7\t4\xd6.\x85*\x0f/x\x97\x06>Kh\xcdD\xfb\xd0h\xa5\x14\xad\x9a\x00||\xbd\xf9\x8fc9\xaa\x8e\xf6?\xad\xb0]s\x95*h\xb1^X\x04s*\x11N*\x1d\xf2\xa9V6\x12S\xdb0<[_\xce\x13\xaaE>\xdb\x8f\xe2]E8-\x06t\x1e\x04\x90\xf5\xd4\xb3)\xfd$\x80\xe9\xban\x16@\x03o~End\x80]8\xbb\xe8.\xfd\xd8\xb8\x03.\xdd\x1dZ\xc8-0\xab:\xd1\x7fa4\xb4\xeb\xc4$\xdc/\xfe\x98\xf6\x19slh\xe5\xee\xbe`P\x19\x1fs\xf2\xf0]t\x99e\xe3\x07Z\x96\xe2P\xed\xd2m\xdd\xca\xec\x8bL\"\xd7\xb2\xb9\xde\xc0\xe3\x92\xa2\xd4\x8c\xd8\xb3+H-O(\x95\x9c\x03m\x94\xe9*\xedvJ\xf1s\x8f\xd6Y\xa2\xdaD7\xe9
q5I\xf1@\xc6\x88\x19\xf9}Z\x19\xa4\x1f\x82Y\xc5]\xea\x91sO\x02\xa5\x05\xc6\x11cj9f\xaa\xa5\xd8T\xe6'
Decrypted: b'Hello, world!'
哈希函数
哈希函数将任意长度的输入变成固定长度的输出,常见的哈希函数有MD5、SHA-1、SHA-256等。
例如实现一个简单的SHA-256哈希函数:
import hashlib
# 哈希函数
def sha256(msg):
return hashlib.sha256(msg.encode()).hexdigest()
使用方法:
msg = 'Hello, world!'
hashed = sha256(msg)
print('Hashed:', hashed)
输出结果:
Hashed: b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9
以上是一些简单的加密和解密算法的实现方法,实际应用中还需考虑更多安全问题和实现细节。
