crypto.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import base64
  2. from Crypto.PublicKey import RSA
  3. from Crypto.Cipher import PKCS1_v1_5 as PKCS1_cipher
  4. from Crypto.Cipher import AES
  5. from functools import wraps
  6. from utils.http import make_json_response
  7. import json
  8. IV = '16-Bytes--String'
  9. with open('public.rsa') as f:
  10. key = f.read()
  11. public_key = RSA.import_key(key)
  12. public_cipher = PKCS1_cipher.new(public_key)
  13. print(public_key.exportKey().decode(encoding='utf-8'))
  14. with open('private.rsa') as f:
  15. key = f.read()
  16. private_key = RSA.import_key(key)
  17. private_cipher = PKCS1_cipher.new(private_key)
  18. # print(private_key.exportKey().decode(encoding='utf-8'))
  19. # 安全传输decorator
  20. def secure_transport(view_func):
  21. @wraps(view_func)
  22. def _wrapped_view(request, *args, **kwargs):
  23. data = request.POST
  24. enc_key = data.get('enc_key')
  25. cipher_text = data.get('cipher_text')
  26. if not enc_key or not cipher_text:
  27. print('无加密')
  28. return view_func(request, *args, **kwargs)
  29. aes_key = private_cipher.decrypt(base64.b64decode(enc_key.encode('utf-8')), b'error').decode('utf-8')
  30. print(f'key={aes_key}')
  31. aes_cipher = AES.new(aes_key.encode('utf-8'), AES.MODE_CBC, IV.encode('utf-8'))
  32. decrypted = aes_cipher.decrypt(base64.b64decode(cipher_text.encode('utf-8')))
  33. # print(decrypted)
  34. decrypted = decrypted[:-decrypted[-1]]
  35. # print(decrypted)
  36. plain_text = decrypted.decode('utf-8')
  37. print(plain_text)
  38. loaded = json.loads(plain_text)
  39. dec_request = request
  40. dec_request.POST = {**request.POST, **loaded}
  41. raw_response = view_func(dec_request, *args, **kwargs)
  42. content = raw_response.content
  43. padding = 16 - len(content) % 16
  44. content += bytes([padding] * padding)
  45. print(content)
  46. aes_cipher = AES.new(aes_key.encode('utf-8'), AES.MODE_CBC, IV.encode('utf-8'))
  47. enc_content = base64.b64encode(aes_cipher.encrypt(content)).decode('utf-8')
  48. print(enc_content)
  49. return make_json_response(enc_content=enc_content)
  50. return _wrapped_view
  51. def test():
  52. plain_text = '{"username": "user1"}'
  53. encrypted = public_cipher.encrypt(bytes(plain_text.encode('utf8')))
  54. cipher_text = base64.b64encode(encrypted)
  55. print(cipher_text.decode('utf8'))
  56. decrypted = private_cipher.decrypt(base64.b64decode(cipher_text), b'error')
  57. print(decrypted.decode('utf8'))
  58. # print(public_key.exportKey().decode('utf-8'))
  59. # random_generator = Random.new().read
  60. # rsa = RSA.generate(2048, random_generator)
  61. # private_key = rsa.exportKey()
  62. # print(private_key.decode('utf-8'))