python3可解密的简单加密方法
程序员文章站
2024-03-14 14:43:04
...
方式一:
# windows下安装依赖包
pip install cryptography
asn1crypto-0.24.0
cffi-1.12.3
cryptography-2.7
pycparser-2.19
six-1.12.0
import base64
import os
from cryptography.fernet import Fernet
class AES():
def __init__(self, secret_key):
self.key = secret_key
def encrypt_p(self, password):
f = Fernet(self.key)
p1 = password.encode()
token = f.encrypt(p1)
p2 = token.decode()
return p2
def decrypt_p(self, password):
f = Fernet(self.key)
p1 = password.encode()
token = f.decrypt(p1)
p2 = token.decode()
return p2
if __name__ == '__main__':
key = base64.urlsafe_b64encode(os.urandom(32))
aes = AES(key)
# 加密
secret_password = aes.encrypt_p('[email protected]')
# 解密
clear_password = aes.decrypt_p(secret_password)
print(clear_password)
方式二:AES对称加密
# windows下安装依赖包
pip install pycryptodomex
# linux下安装依赖包
pip install pycryptodome
pycryptodomex-3.8.2
# windows下导包
from Cryptodome.Cipher import AES
# linux下导包
from Crypto.Cipher import AES
from binascii import b2a_hex, a2b_hex
class prpcrypt():
def __init__(self, key):
self.key = self.handle_length(key)
self.mode = AES.MODE_CBC
def handle_length(self, text):
# 这里**key 长度必须为16(AES-128)、24(AES-192)、或32(AES-256)Bytes 长度.目前AES-128足够用
length = 16
count = len(text)
if (count % length != 0):
add = length - (count % length)
else:
add = 0
text = text + ('\0' * add)
return text.encode()
# 加密函数【加密文本text必须为16的倍数!】,如果text不是16的倍数,那就补足16位
def encrypt(self, text):
text = self.handle_length(text)
cryptor = AES.new(self.key, self.mode, self.key)
ciphertext = cryptor.encrypt(text)
# 因为AES加密时候得到的字符串不一定是ascii字符集的,输出到终端或者保存时候可能存在问题
# 所以这里统一把加密后的字符串转化为16进制字符串
return b2a_hex(ciphertext).decode()
# 解密函数
def decrypt(self, text):
cryptor = AES.new(self.key, self.mode, self.key)
plain_text = cryptor.decrypt(a2b_hex(text))
# 去掉加密时填补的空格,使用strip()
return plain_text.decode().rstrip('\0')
if __name__ == '__main__':
pc = prpcrypt('ecloud') # 初始化**,小于等于16位
e = pc.encrypt("[email protected]")
d = pc.decrypt(e)
print(e, d)
上一篇: //set()的使用
下一篇: Base32 应用与原理解析