Python MD5加密的三种方法(可加盐)/base64加解密 /RSA加解密

一、实现MD5加密

方法一:MD5直接加密

import hashlib


# 定义用户名和密码
username = 'admin'
password = '123'

# 计算用户名的MD5哈希值
md = hashlib.md5(username.encode())
md5username = md.hexdigest()
print(md5username)

# 计算密码的MD5哈希值
md = hashlib.md5(password.encode())
md5password = md.hexdigest()
print(md5password)

运行看结果:

21232f297a57a5a743894a0e4a801fc3
202cb962ac59075b964b07152d234b70

建议加密是否正确:

方法二:MD5+盐加密,将盐拼接在原密码后

import hashlib

text1='123456'
print(text1)
SALE=text1[:4]	# 设置盐值
print(str(text1)+SALE)
md_sale=hashlib.md5((text1+SALE).encode()) # MD5加盐加密方法一:将盐拼接在原密码后
md5salepwd=md_sale.hexdigest()
print(md5salepwd)        

输出结果:

方法三:MD5+盐加密,将password整体插入SALE的每个元素之间

import hashlib

text1='123456'
print(text1)
SALE=text1[:4]	# 设置盐值
print(str(text1).join(SALE))
md_sale=hashlib.md5((str(text1).join(SALE)).encode())  # MD5加盐加密方法二:将password整体插入SALE的每个元素之间
md5salepwd=md_sale.hexdigest()
print(md5salepwd)        

输出结果:

二、实现base64加密解密

1、Python实现base64加密,可以使用base64库。

代码如下:

import base64


# 加密
username = "admin"
base64_username = base64.b64encode(username.encode('utf-8')).decode()
print(base64_username)
password = "123"
base64_password = base64.b64encode(password.encode('utf-8')).decode()
print(base64_password)

运行结果:

YWRtaW4=
MTIz


Process finished with exit code 0

对比结果:

2、 Python实现base64解密,可以使用base64库。

import base64
import requests

# 加密
username = "admin"
base64_username = base64.b64encode(username.encode('utf-8')).decode()
print(base64_username)
password = "123"
base64_password = base64.b64encode(password.encode('utf-8')).decode()
print(base64_password)

data={'username':base64_username,'password':base64_password}
response=requests.post("http://*****:5000/base64login",params=data)
print(response.json())

# 解密
str1 = base64.b64decode(base64_username.encode('utf-8')).decode()
print(str1)
str2 = base64.b64decode(base64_password.encode('utf-8')).decode()
print(str2)

打印结果:

YWRtaW4=
MTIz
{'error_code': 0, 'message': 'Base64加密登陆成功!'}
admin
123

Process finished with exit code 0

三、实现RSA加密解密

一、RSA加密算法

RSA加密算法是一种非对称加密算法,加密的秘钥是由公钥和私钥两部分组成秘钥对,公钥用来加密消息,私钥用来解密消息,公钥是公开的,给对方进行加密,私钥则是用户自己保留,用来对加密的数据进行解密。

公钥pem文件格式:以-----BEGIN PUBLIC KEY-----标记打头,以-----END PUBLIC KEY-----标记结尾,中间部分即为公钥

-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDM6dGIA2naE3nGXi6O9vHskRSj
uC5hn30msl+bk1yJl4NUqH1et7S3C0NWMDHPkC0vyWtp8HTpV1bFN747zToegLOs
n1+zsf1LSObVce+UU76w1J3oAHBPCHSTt+WuTe+FMbQzvX1CQAdzdqCvYFvb+b9Y
+L+ajto9raO0cfdGawIDAQAB
-----END PUBLIC KEY-----

私钥pem文件格式:以-----BEGIN RSA PRIVATE KEY-----打头,以-----END RSA PRIVATE KEY-----结尾,中间部分即为私钥

-----BEGIN RSA PRIVATE KEY-----
MIICWwIBAAKBgQDM6dGIA2naE3nGXi6O9vHskRSjuC5hn30msl+bk1yJl4NUqH1e
t7S3C0NWMDHPkC0vyWtp8HTpV1bFN747zToegLOsn1+zsf1LSObVce+UU76w1J3o
AHBPCHSTt+WuTe+FMbQzvX1CQAdzdqCvYFvb+b9Y+L+ajto9raO0cfdGawIDAQAB
AoGACjUBb22AGdFLiRKK7isl3NtTNF6JzOoVYVaURZsfCmmGLLLh39R1x4Jjncjz
yjuLzKwTUikcobzsgRFoQ/FSmjiMkQcIFoE20qJiYOOnB8T346OZfyWSMQqTAWTa
KnT1Ih74x2aft4Sf3NwkDpqEqU4nksEWmebZ+ynStaCaHKkCQQDj1FN0D8b2knbl
m0SXvDwhKX4R6U+ZZtDR1XwLwlFuz9xSFfuQ797O91pJwHagB8jWkCSYYDeIDyYd
hQCDcRIzAkEA5kAcnyryeORaMbuvHqq+fulff+u0bp4Crply4qKI5PV2wVskQ1z0
DzRyao8n9rED+kxYM5E5HXc4q9nkzUFy6QJAauTrRvBEHNp5eJ9SHpNN7w1Fvmem
VkY8QceVjPreNEzIhacUwlsZQigiL6pivhEI9UrqMKgsReU9r+oAZKt/qwJAU5Pg
D9K6EzHon3beOUaHQXAa70cyxphqptAiiKuw/1MumT8pKZ6bJM3H3nA6dGyK4hdG
SOmlDtIQ6yh7yhnAyQJAPKCoBoiR6f+feOwBrrh0KTbHucZygH4y9bPW+tz5nrwt
ChypQ8vu7qG7Arcw9jYJ2HJFXHeQ3Hx2FjhruYfwew==
-----END RSA PRIVATE KEY-----

二、使用Python进行RSA加密解密

1、模块安装
pip install pycryptodome -i https://pypi.tuna.tsinghua.edu.cn/simple
2、代码示例
import base64
from Crypto import Random
from Crypto.Cipher import PKCS1_v1_5
from Crypto.PublicKey import RSA

# 伪随机数生成器
random_generator = Random.new().read
# rsa算法生成秘钥对实例对象:1024是秘钥的长度
rsa = RSA.generate(1024, random_generator)


#生成私钥并保存到pem文件,如果知道秘钥值key3也可以不保存,拼接上begin/end标识后加载直接用,如key3 = '-----BEGIN PUBLIC KEY-----
' + key3 + '
' + '-----END PUBLIC KEY-----'
private_pem = rsa.exportKey()
#print(private_pem)
with open("./private.pem", "wb") as f:  #wb,以二进制格式写入文件到当前文件夹中
    f.write(private_pem)


#生成公钥并保存到pem文件,当然也可以不保存直接用,即key1
public_pem = rsa.publickey().exportKey()
with open("./public.pem", "wb") as f: #wb,以二进制格式写入文件
    f.write(public_pem)

#plaintext:需要加密的明文文本,公钥加密,私钥解密
plaintext = 'admin'

#加密过程
# 1:加载公钥
with open("public.pem") as f1:
    key1 = f1.read()  #从pem文件中读取公钥内容,包括begin头/end尾标识
    public_key = RSA.import_key(key1) #加载公钥key1

#:2:加密
cipher_rsa = PKCS1_v1_5.new(public_key)
#cipher_text 即为加密后的密文
cipher_text = base64.b64encode(cipher_rsa.encrypt(plaintext.encode('utf-8')))

#打印加密结果
#Python3的字符串的编码语言用的是unicode编码,由于Python的字符串类型是str,如果直接打印出来print(cipher_text),会是b'字符串',解决方案是后面添加decode('utf-8')
print(cipher_text.decode('utf-8'))


# 读取私钥
with open("private.pem") as f2:
    key2 = f2.read()#从pem文件中读取私钥内容,包括begin头/end尾标识
    private_key = RSA.import_key(key2)#加载私钥key2

# 解密
cipher_rsa = PKCS1_v1_5.new(private_key)
text = cipher_rsa.decrypt(base64.b64decode(cipher_text),random_generator)
#打印解密结果
#Python3的字符串的编码语言用的是unicode编码,由于Python的字符串类型是str,如果直接打印出来print(text),会是b'字符串',解决方案是后面添加decode('utf-8')
print(text.decode('utf-8'))
3、运行结果
uORTWLnlQ8IdBY3BJIQjeaPfL7aAvBf8VB0zku6LKRZJvK2vlqEyX77i7JPXx7b4OrK86/c93McR72oOdujY5PY/K6aAXz0FYmkN01s6eYfFC5ODRLxgCuVuE+6+QLUc3b8kYOQ11Q3sXRnCJyjWdeGu/IkBZ3WSn8WlHxCDSK8=
admin

Process finished with exit code 0
4、代码示例2
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
import base64

# 生成RSA密钥对
key = RSA.generate(2048)

# 加密数据
public_key = key.publickey()
cipher = PKCS1_OAEP.new(public_key)
encrypted_data = cipher.encrypt(b'admin')
encoded_encrypted_data = base64.b64encode(encrypted_data)
print(encoded_encrypted_data.decode('utf-8'))

# 解密数据
cipher = PKCS1_OAEP.new(key)
decoded_encrypted_data = base64.b64decode(encoded_encrypted_data)
decrypted_data = cipher.decrypt(decoded_encrypted_data)
print(decrypted_data.decode())

运行结果

PZssDKs036HTNWA/EGKIF9m5S+8LZ9vNadzXzx19tLsT1F7M4JZHYGlS0ep54q5ICSp4daPR2RZMjRfotQiWZrUE1MWz25N1ocyegtbFplscOczhJ33RYGmVheCfJnV+Hxkxu77S0K0GACeRwRRZ8XcSmgMAqZ0EiDKgpNZ5NBweDtula0oH26gQa8o5fB49AwZ28JEGaWsTeuDiLgG/u3fotqcDFqY2bMeFntISNQ5MzSI1RNdIuK73phFNgIlELmw14i3UrYlSEJdpwj2IrQeYZbXQzEzQA0mDRnUvRzF/pCKX3Kg7rnAcERszhpuKzAzGZSQEEjnUGAq3tXvvfw==
admin

Process finished with exit code 0