https://pypi.org/project/pycrypto/
停止使用 pycrypto

  1. 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)

  1. <a name="IJFT6"></a>
  2. ### aes ecb
  3. ECB加密不需要iv
  4. ```python
  5. import base64
  6. from Crypto.Cipher import AES
  7. '''
  8. 采用AES对称加密算法
  9. '''
  10. # str不是32的倍数那就补足为16的倍数
  11. def add_to_32(value):
  12. while len(value) % 32 != 0:
  13. value += '\0'
  14. return str.encode(value) # 返回bytes
  15. def add_to_16(value):
  16. while len(value) % 16 != 0:
  17. value += '\0'
  18. return str.encode(value) # 返回bytes
  19. #加密方法
  20. def encrypt_oracle(text):
  21. # 秘钥
  22. key = 'VW1lMjAxMlRyaXAwMzA5AA=='
  23. # 待加密文本
  24. # 初始化加密器
  25. aes = AES.new(add_to_16(key), AES.MODE_ECB)
  26. #先进行aes加密
  27. encrypt_aes = aes.encrypt(add_to_16(text))
  28. #用base64转成字符串形式
  29. encrypted_text = str(base64.encodebytes(encrypt_aes), encoding='utf-8') # 执行加密并转码返回bytes
  30. print(encrypted_text)
  31. return encrypted_text
  32. #解密方法
  33. def decrypt_oralce(text):
  34. # 秘钥
  35. key = 'VW1lMjAxMlRyaXAwMzA5AA=='
  36. # 密文
  37. # 初始化加密器
  38. aes = AES.new(add_to_16(key), AES.MODE_ECB)
  39. #优先逆向解密base64成bytes
  40. base64_decrypted = base64.decodebytes(text.encode(encoding='utf-8'))
  41. #执行解密密并转码返回str
  42. decrypted_text = str(aes.decrypt(base64_decrypted),encoding='utf-8').replace('\0','')
  43. print('decrypted_text',decrypted_text)
  44. return decrypted_text
  45. if __name__ == '__main__':
  46. text = '''{'aaa': '111', 'bbb': '222'}'''
  47. entrypted_text = encrypt_oracle(text)
  48. decrypt_oralce(entrypted_text)