Python MD5加密的三种方法(可加盐)/base64加解密 /RSA加解密
import hashlib
import base64
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
import rsa
# MD5加密
def md5_encryption(data):
md5 = hashlib.md5()
md5.update(data.encode('utf-8'))
return md5.hexdigest()
# MD5加盐加密
def md5_salt_encryption(data, salt):
md5 = hashlib.md5(salt.encode('utf-8'))
md5.update(data.encode('utf-8'))
return md5.hexdigest()
# 使用base64进行加密解密
def base64_encryption(data):
return base64.b64encode(data.encode('utf-8')).decode('utf-8')
def base64_decryption(data):
return base64.b64decode(data.encode('utf-8')).decode('utf-8')
# AES加密解密
def aes_encryption(data, key):
pad = AES.block_size - len(data) % AES.block_size
data = data + pad * chr(pad)
iv = get_random_bytes(AES.block_size)
cipher = AES.new(key, AES.MODE_CFB, iv)
return iv + cipher.encrypt(data)
def aes_decryption(data, key):
iv = data[:AES.block_size]
cipher = AES.new(key, AES.MODE_CFB, iv)
return cipher.decrypt(data[AES.block_size:]).rstrip(chr(AES.block_size))
# RSA加密解密
def rsa_encryption(data, pub_key):
return rsa.encrypt(data.encode('utf-8'), pub_key)
def rsa_decryption(data, priv_key):
return rsa.decrypt(data, priv_key).decode('utf-8')
# 生成RSA密钥对
def generate_rsa_keys():
(pub_key, priv_key) = rsa.newkeys(1024)
return (pub_key, priv_key)
# 示例
if __name__ == '__main__':
data = 'Hello, World!'
salt = 'secret_salt'
key = b'1234567890123456'
pub_key, priv_key = generate_rsa_keys()
print('MD5加密:', md5_encryption(data))
print('MD5加盐加密:', md5_salt_encryption(data, salt))
print('Base64加密:', base64_encryption(data))
print('Base64解密:', base64_decryption(base64_encryption(data)))
print('AES加密:', aes_encryption(data, key))
print('AES解密:', aes_decryption(aes_encryption(data, key), key))
print('RSA加密:', rsa_encryption(data, pub_key))
print('RSA解密:', rsa_decryption(rsa_encryption(data, pub_key), priv_key))
注意:
- 示例中使用的RSA加密需要安装
rsa
库,可以通过pip install rsa
进行安装。 - AES加密需要安装
pycryptodome
库,可以通过pip install pycryptodome
进行安装。 - 示例中的密钥和盐仅为示例使用,实际应用中需要使用强随机密钥和盐。
- 示例中的AES加密模式(CFB)和块大小(128)可能需要根据实际需求进行调整。
评论已关闭