对称解密
-
所谓对称加密就是加密和解密用的是同一个秘钥. 就好比. 我要给你邮寄一个箱子. 上面怼上锁. 提前我把钥匙给了你一把, 我一把. 那么我在邮寄之前就可以把箱子锁上. 然后快递到你那里. 你用相同的钥匙就可以打开这个箱子.
-
常见的对称加密: AES, DES, 3DES等
安装第三方模块
- pip install pycrypto => 很多人装不上....
- pip install pycryptodome => 可以装..
- AES源码
# 创建加密器
# 秘钥必须是 16, 24, 32位字节...
# 99%的网站使用的aes都是16位秘钥..
# mode: AES的加密方式
# 常见的mode:
# ECB, 可以没有iv
# CBC, 必须有iv. 长度是16字节..
def new(key, mode, *args, **kwargs):
"""Create a new AES cipher.
Args:
key(bytes/bytearray/memoryview):
The secret key to use in the symmetric cipher.
It must be 16 (*AES-128)*, 24 (*AES-192*) or 32 (*AES-256*) bytes long.
For ``MODE_SIV`` only, it doubles to 32, 48, or 64 bytes.
mode (a ``MODE_*`` constant):
The chaining mode to use for encryption or decryption.
If in doubt, use ``MODE_EAX``.
Keyword Args:
iv (bytes/bytearray/memoryview):
(Only applicable for ``MODE_CBC``, ``MODE_CFB``, ``MODE_OFB``,
and ``MODE_OPENPGP`` modes).
The initialization vector to use for encryption or decryption.
For ``MODE_CBC``, ``MODE_CFB``, and ``MODE_OFB`` it must be 16 bytes long.
For ``MODE_OPENPGP`` mode only,
it must be 16 bytes long for encryption
and 18 bytes for decryption (in the latter case, it is
actually the *encrypted* IV which was prefixed to the ciphertext).
If not provided, a random byte string is generated (you must then
read its value with the :attr:`iv` attribute).
"""
使用案例
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad,unpad
import base64,json
## 加密
def encrypt(s:str):
# 准备加密器
aes = AES.new(key=b'1234567890123456',mode=AES.MODE_CBC,iv=b'qwertyuioplkjhgf')
#将需要加密的数据处理成字节
bs = s.encode()
# 要求数据的长度必须是16的倍数.不够的需要填充.
bs_pad = pad(bs,16) # 默认的填充方式 pkcs7
# 加密
mi_wen = aes.encrypt(bs_pad)
#加密后是字节,需要使用base64编码后 还原成字符串
ret = base64.b64encode(mi_wen).decode()
return ret # rIRmEG7oqVCFOEvaCjTMlXH+BjhluQVp6l/Hq6guEHM=
## 解密
def decrypt(s:str):
# 创建解密器
aes2 = AES.new(key=b'1234567890123456',mode=AES.MODE_CBC,iv=b'qwertyuioplkjhgf')
# 将密文转换成字节
mi_bs = base64.b64decode(s)
#解密
ming_bs = aes2.decrypt(mi_bs)
#解密后,去除填充---解码成字符串
ret2 = unpad(ming_bs,16).decode('utf-8')
return ret2
if __name__ == '__main__':
dic = {
"name": "xwl",
"password": 18
}
s = json.dumps(dic,separators=(',', ':'))
miwen = encrypt(s)
print(f'miwen===>{miwen}')
mingwen = decrypt(miwen)
print(f'mingwen===>>>{mingwen}')
""""
运行结果
miwen===>rIRmEG7oqVCFOEvaCjTMlXH+BjhluQVp6l/Hq6guEHM=
mingwen===>>>{"name":"xwl","password":18}
"""
DES加密
- 与AES几乎一致
from Crypto.Cipher import DES, AES, DES3
from Crypto.Util.Padding import pad, unpad
import base64
# s = "雪中悍刀行"
# des = DES.new(key=b'12345678', mode=DES.MODE_CBC, iv=b'55511122')
# result = des.encrypt(pad(s.encode("utf-8"), 8))
# print(base64.b64encode(result).decode())
# # DES解密
# s = "KTF6QlkTXPN1qhcBtm6mUzZh4XLqzJsw"
# des = DES.new(key=b'12345678', mode=DES.MODE_CBC, iv=b'55511122')
# ming_bs = des.decrypt(base64.b64decode(s))
# print(unpad(ming_bs, 8).decode("utf-8"))
标签:web,AES,16,08,DES,mode,bs,MODE
From: https://www.cnblogs.com/xwltest/p/17636449.html