Advertisement
den4ik2003

Untitled

Nov 25th, 2024
28
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.79 KB | None | 0 0
  1. from cryptography.hazmat.primitives import serialization
  2. from cryptography.hazmat.primitives.asymmetric import rsa
  3. from cryptography.hazmat.backends import default_backend
  4. from cryptography.hazmat.primitives import hashes
  5. from cryptography.hazmat.primitives.asymmetric import padding
  6.  
  7. class CryptoManager:
  8. def __init__(self):
  9. self.private_key = ""
  10. self.public_key = ""
  11.  
  12. def generate_and_write_keys(self, path_to_private_key, path_to_public_key):
  13. key = rsa.generate_private_key(
  14. backend=default_backend(),
  15. public_exponent=65537,
  16. key_size=2048
  17. )
  18.  
  19. private_key = key.private_bytes(
  20. serialization.Encoding.PEM,
  21. serialization.PrivateFormat.PKCS8,
  22. serialization.NoEncryption(),
  23. )
  24.  
  25. public_key = key.public_key().public_bytes(
  26. serialization.Encoding.OpenSSH,
  27. serialization.PublicFormat.OpenSSH
  28. )
  29.  
  30. with open(path_to_private_key, 'w') as file:
  31. file.write(private_key.decode('utf-8'))
  32.  
  33. with open(path_to_public_key, 'w') as file:
  34. file.write(public_key.decode('utf-8'))
  35.  
  36.  
  37. def load_keys(self, path_to_key_file):
  38. with open(path_to_key_file, "rb") as key_file:
  39. key = serialization.load_pem_private_key(
  40. key_file.read(),
  41. password=None,
  42. )
  43.  
  44. self.private_key = key.private_bytes(
  45. serialization.Encoding.PEM,
  46. serialization.PrivateFormat.PKCS8,
  47. serialization.NoEncryption(),
  48. )
  49.  
  50. self.public_key = key.public_key().public_bytes(
  51. serialization.Encoding.OpenSSH,
  52. serialization.PublicFormat.OpenSSH
  53. )
  54.  
  55. self.key = key
  56. self.pubkey = key.public_key()
  57.  
  58. def encrypt_message_with_key_from_file(self, path_to_public_key, message):
  59. with open(path_to_public_key, "rb") as key_file:
  60. pubkey = serialization.load_pem_public_key(
  61. key_file.read(),
  62. password=None,
  63. )
  64.  
  65. return pubkey.encrypt(
  66. message,
  67. padding.OAEP(
  68. mgf=padding.MGF1(algorithm=hashes.SHA256()),
  69. algorithm=hashes.SHA256(),
  70. label=None
  71. )
  72. )
  73.  
  74. def decrypt_message(self, encoded_message): # обработка когда не дешифруется
  75. text = self.key.decrypt(
  76. encoded_message,
  77. padding.OAEP(
  78. mgf=padding.MGF1(algorithm=hashes.SHA256()),
  79. algorithm=hashes.SHA256(),
  80. label=None
  81. )
  82. ).decode('utf-8')
  83.  
  84. return text
  85.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement