example08.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. """
  2. 加密和解密
  3. 对称加密 - 加密和解密是同一个密钥 - DES / AES
  4. 非对称加密 - 加密和解密是不同的密钥 - RSA
  5. pip install pycrypto
  6. """
  7. import base64
  8. from hashlib import md5
  9. from Crypto.Cipher import AES
  10. from Crypto import Random
  11. from Crypto.PublicKey import RSA
  12. # # AES加密的密钥(长度32个字节)
  13. # key = md5(b'1qaz2wsx').hexdigest()
  14. # # AES加密的初始向量(随机生成)
  15. # iv = Random.new().read(AES.block_size)
  16. def main():
  17. """主函数"""
  18. # 生成密钥对
  19. key_pair = RSA.generate(1024)
  20. # 导入公钥
  21. pub_key = RSA.importKey(key_pair.publickey().exportKey())
  22. # 导入私钥
  23. pri_key = RSA.importKey(key_pair.exportKey())
  24. message1 = 'hello, world!'
  25. # 加密数据
  26. data = pub_key.encrypt(message1.encode(), None)
  27. # 对加密数据进行BASE64编码
  28. message2 = base64.b64encode(data[0])
  29. print(message2)
  30. # 对加密数据进行BASE64解码
  31. data = base64.b64decode(message2)
  32. # 解密数据
  33. message3 = pri_key.decrypt(data)
  34. print(message3.decode())
  35. # # AES - 对称加密
  36. # str1 = '我爱你们!'
  37. # cipher = AES.new(key, AES.MODE_CFB, iv)
  38. # # 加密
  39. # str2 = cipher.encrypt(str1)
  40. # print(str2)
  41. # # 解密
  42. # cipher = AES.new(key, AES.MODE_CFB, iv)
  43. # str3 = cipher.decrypt(str2)
  44. # print(str3.decode())
  45. if __name__ == '__main__':
  46. main()