den4ik2003

Untitled

Nov 25th, 2024
23
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.80 KB | None | 0 0
  1. import os
  2. import base64
  3. from cryptography.hazmat.primitives import serialization
  4. from cryptography.hazmat.primitives.asymmetric import rsa
  5. from cryptography.hazmat.backends import default_backend
  6. from cryptography.hazmat.primitives import hashes
  7. from cryptography.hazmat.primitives import padding
  8. from cryptography.hazmat.primitives.asymmetric import padding as asymetric_padding
  9. from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
  10.  
  11. class SymetricCryptomanager:
  12.     def __init__(self, path_to_key):
  13.         if os.path.exists(path_to_key):
  14.             with open(path_to_key, "rb") as file:
  15.                 self.key = file.read()
  16.         else:
  17.             with open(path_to_key, "wb") as file:
  18.                 self.key = os.urandom(32)
  19.                 file.write(self.key)
  20.  
  21.     def encrypt_message(self, message):
  22.         # Pad the message to make its size a multiple of block size
  23.         padder = padding.PKCS7(algorithms.AES.block_size).padder()  # AES block size is 128 bits
  24.         padded_message = padder.update(message) + padder.finalize()
  25.  
  26.         iv = os.urandom(16)  # Initialization vector
  27.         cipher = Cipher(algorithms.AES(self.key), modes.CBC(iv))
  28.         encryptor = cipher.encryptor()
  29.         tmp = encryptor.update(padded_message) + encryptor.finalize()
  30.         return base64.b64encode(iv + tmp)
  31.  
  32.     def decrypt_message(self, encoded_message):
  33.         try:
  34.             decoded_data = base64.b64decode(encoded_message)  # Decode the base64 data
  35.             iv = decoded_data[:16]
  36.             cipher = Cipher(algorithms.AES(self.key), modes.CBC(iv))
  37.             decryptor = cipher.decryptor()
  38.             padded_plaintext = decryptor.update(decoded_data[16:]) + decryptor.finalize()
  39.  
  40.             # Unpad the plaintext
  41.             unpadder = padding.PKCS7(algorithms.AES.block_size).unpadder()
  42.             plaintext = unpadder.update(padded_plaintext) + unpadder.finalize()
  43.             return plaintext.decode('utf-8')
  44.         except Exception as e:
  45.             print(f"Decryption error: {e}")
  46.             return ""
  47.  
  48.  
  49. class AsymetricCryptoManager:
  50.  
  51.     def __init__(self, name, path_to_private_key):
  52.         if os.path.exists(path_to_private_key):
  53.             with open(path_to_private_key, "rb") as key_file:
  54.                 self.private_key = serialization.load_pem_private_key(
  55.                     key_file.read(),
  56.                     password=None,
  57.                 )
  58.         else:
  59.             self.generate_and_write_keys(path_to_private_key, '/'.join(path_to_private_key.split('/')[:-1]) + f'/{name}.pem')
  60.  
  61.  
  62.     def generate_and_write_keys(self, path_to_private_key, path_to_public_key):
  63.         self.private_key = rsa.generate_private_key(
  64.             backend=default_backend(),
  65.             public_exponent=65537,
  66.             key_size=2048
  67.         )
  68.  
  69.         private_key = self.private_key.private_bytes(
  70.             serialization.Encoding.PEM,
  71.             serialization.PrivateFormat.PKCS8,
  72.             serialization.NoEncryption(),
  73.         )
  74.  
  75.         public_key = self.private_key.public_key().public_bytes(
  76.             encoding=serialization.Encoding.PEM,
  77.             format=serialization.PublicFormat.SubjectPublicKeyInfo
  78.         )
  79.  
  80.         with open(path_to_private_key, 'w') as file:
  81.             file.write(private_key.decode('utf-8'))
  82.            
  83.         with open(path_to_public_key, 'w') as file:
  84.             file.write(public_key.decode('utf-8'))
  85.  
  86.  
  87.     def encrypt_message_with_key_from_file(self, path_to_public_key, message):
  88.         with open(path_to_public_key, "rb") as key_file:
  89.             pubkey = serialization.load_pem_public_key(
  90.                 key_file.read(),
  91.                 backend=default_backend()
  92.             )
  93.  
  94.         return pubkey.encrypt(
  95.             message,
  96.             asymetric_padding.OAEP(
  97.                 mgf=asymetric_padding.MGF1(algorithm=hashes.SHA256()),
  98.                 algorithm=hashes.SHA256(),
  99.                 label=None
  100.             )
  101.         )
  102.        
  103.     def decrypt_message(self, encoded_message): # обработка когда не дешифруется
  104.         try:
  105.             text = self.private_key.decrypt(
  106.                 encoded_message,
  107.                 asymetric_padding.OAEP(
  108.                     mgf=asymetric_padding.MGF1(algorithm=hashes.SHA256()),
  109.                     algorithm=hashes.SHA256(),
  110.                     label=None
  111.                 )
  112.             ).decode('utf-8')
  113.  
  114.             return text
  115.  
  116.         except:
  117.             return ""
  118.  
  119. # crypto = AsymetricCryptoManager('denis', '/home/ubuntu/abradabra/private_1.pem')
  120. # msg = 'hello'
  121. # print(crypto.decrypt_message(crypto.encrypt_message_with_key_from_file('denis.pem', msg.encode())))
  122.  
  123. # crypto = SymetricCryptomanager('sym.key')
  124. # msg = 'hello sss'
  125. # print(crypto.decrypt_message(crypto.encrypt_message(msg.encode())))
  126.  
Add Comment
Please, Sign In to add comment