原文链接

    AES加密方式有五种:ECB, CBC, CTR, CFB, OFB

    从安全性角度推荐CBC加密方法,本文介绍了CBC,ECB两种加密方法的python实现

    python 在 Windows 下使用AES时要安装的是pycryptodome 模块 pip install pycryptodome

    python 在 Linux 下使用AES时要安装的是pycrypto模块 pip install pycrypto

    CBC加密需要一个十六位的key(密钥)和一个十六位iv(偏移量)

    ECB加密不需要iv

    1. ```python
    2. CBC 加密的python实现
    3. ```python
    4. 1 from Crypto.Cipher import AES
    5. 2 from binascii import b2a_hex, a2b_hex
    6. 3
    7. 4
    8. 5 # 如果text不足16位的倍数就用空格补足为16位
    9. 6 def add_to_16(text):
    10. 7 if len(text.encode('utf-8')) % 16:
    11. 8 add = 16 - (len(text.encode('utf-8')) % 16)
    12. 9 else:
    13. 10 add = 0
    14. 11 text = text + ('\0' * add)
    15. 12 return text.encode('utf-8')
    16. 13
    17. 14
    18. 15 # 加密函数
    19. 16 def encrypt(text):
    20. 17 key = '9999999999999999'.encode('utf-8')
    21. 18 mode = AES.MODE_CBC
    22. 19 iv = b'qqqqqqqqqqqqqqqq'
    23. 20 text = add_to_16(text)
    24. 21 cryptos = AES.new(key, mode, iv)
    25. 22 cipher_text = cryptos.encrypt(text)
    26. 23 # 因为AES加密后的字符串不一定是ascii字符集的,输出保存可能存在问题,所以这里转为16进制字符串
    27. 24 return b2a_hex(cipher_text)
    28. 25
    29. 26
    30. 27 # 解密后,去掉补足的空格用strip() 去掉
    31. 28 def decrypt(text):
    32. 29 key = '9999999999999999'.encode('utf-8')
    33. 30 iv = b'qqqqqqqqqqqqqqqq'
    34. 31 mode = AES.MODE_CBC
    35. 32 cryptos = AES.new(key, mode, iv)
    36. 33 plain_text = cryptos.decrypt(a2b_hex(text))
    37. 34 return bytes.decode(plain_text).rstrip('\0')
    38. 35
    39. 36
    40. 37 if __name__ == '__main__':
    41. 38 e = encrypt("hello world") # 加密
    42. 39 d = decrypt(e) # 解密
    43. 40 print("加密:", e)
    44. 41 print("解密:", d)

    AES ECB加密的python实现

    1. 1 """
    2. 2 ECB没有偏移量
    3. 3 """
    4. 4 from Crypto.Cipher import AES
    5. 5 from binascii import b2a_hex, a2b_hex
    6. 6
    7. 7
    8. 8 def add_to_16(text):
    9. 9 if len(text.encode('utf-8')) % 16:
    10. 10 add = 16 - (len(text.encode('utf-8')) % 16)
    11. 11 else:
    12. 12 add = 0
    13. 13 text = text + ('\0' * add)
    14. 14 return text.encode('utf-8')
    15. 15
    16. 16
    17. 17 # 加密函数
    18. 18 def encrypt(text):
    19. 19 key = '9999999999999999'.encode('utf-8')
    20. 20 mode = AES.MODE_ECB
    21. 21 text = add_to_16(text)
    22. 22 cryptos = AES.new(key, mode)
    23. 23
    24. 24 cipher_text = cryptos.encrypt(text)
    25. 25 return b2a_hex(cipher_text)
    26. 26
    27. 27
    28. 28 # 解密后,去掉补足的空格用strip() 去掉
    29. 29 def decrypt(text):
    30. 30 key = '9999999999999999'.encode('utf-8')
    31. 31 mode = AES.MODE_ECB
    32. 32 cryptor = AES.new(key, mode)
    33. 33 plain_text = cryptor.decrypt(a2b_hex(text))
    34. 34 return bytes.decode(plain_text).rstrip('\0')
    35. 35
    36. 36
    37. 37 if __name__ == '__main__':
    38. 38 e = encrypt("hello world") # 加密
    39. 39 d = decrypt(e) # 解密
    40. 40 print("加密:", e)
    41. 41 print("解密:", d)