https://pypi.org/project/pycrypto/
停止使用 pycrypto
pip install pycrypto
aes
- cbc CBC加密需要一个十六位的key(密钥)和一个十六位iv(偏移量)
- ecb ECB加密不需要iv
aes cbc
CBC加密需要一个十六位的key(密钥)和一个十六位iv(偏移量) ``` from Crypto.Cipher import AES from binascii import b2a_hex, a2b_hex
如果text不足16位的倍数就用空格补足为16位
def add_to_16(text): if len(text.encode(‘utf-8’)) % 16: add = 16 - (len(text.encode(‘utf-8’)) % 16) else: add = 0 text = text + (‘\0’ * add) return text.encode(‘utf-8’)
加密函数
def encrypt(text): key = ‘9999999999999999’.encode(‘utf-8’) mode = AES.MODE_CBC iv = b’qqqqqqqqqqqqqqqq’ text = add_to_16(text) cryptos = AES.new(key, mode, iv) cipher_text = cryptos.encrypt(text)
因为AES加密后的字符串不一定是ascii字符集的,输出保存可能存在问题,所以这里转为16进制字符串
return b2a_hex(cipher_text)
解密后,去掉补足的空格用strip() 去掉
def decrypt(text): key = ‘9999999999999999’.encode(‘utf-8’) iv = b’qqqqqqqqqqqqqqqq’ mode = AES.MODE_CBC cryptos = AES.new(key, mode, iv) plain_text = cryptos.decrypt(a2b_hex(text)) return bytes.decode(plain_text).rstrip(‘\0’)
if name == ‘main‘: e = encrypt(“hello world”) # 加密 d = decrypt(e) # 解密 print(“加密:”, e) print(“解密:”, d)
<a name="IJFT6"></a>
### aes ecb
ECB加密不需要iv
```python
import base64
from Crypto.Cipher import AES
'''
采用AES对称加密算法
'''
# str不是32的倍数那就补足为16的倍数
def add_to_32(value):
while len(value) % 32 != 0:
value += '\0'
return str.encode(value) # 返回bytes
def add_to_16(value):
while len(value) % 16 != 0:
value += '\0'
return str.encode(value) # 返回bytes
#加密方法
def encrypt_oracle(text):
# 秘钥
key = 'VW1lMjAxMlRyaXAwMzA5AA=='
# 待加密文本
# 初始化加密器
aes = AES.new(add_to_16(key), AES.MODE_ECB)
#先进行aes加密
encrypt_aes = aes.encrypt(add_to_16(text))
#用base64转成字符串形式
encrypted_text = str(base64.encodebytes(encrypt_aes), encoding='utf-8') # 执行加密并转码返回bytes
print(encrypted_text)
return encrypted_text
#解密方法
def decrypt_oralce(text):
# 秘钥
key = 'VW1lMjAxMlRyaXAwMzA5AA=='
# 密文
# 初始化加密器
aes = AES.new(add_to_16(key), AES.MODE_ECB)
#优先逆向解密base64成bytes
base64_decrypted = base64.decodebytes(text.encode(encoding='utf-8'))
#执行解密密并转码返回str
decrypted_text = str(aes.decrypt(base64_decrypted),encoding='utf-8').replace('\0','')
print('decrypted_text',decrypted_text)
return decrypted_text
if __name__ == '__main__':
text = '''{'aaa': '111', 'bbb': '222'}'''
entrypted_text = encrypt_oracle(text)
decrypt_oralce(entrypted_text)