sidqdev

Untitled

Aug 16th, 2022
34
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.54 KB | None | 0 0
  1. import hashlib
  2. from Crypto import Random
  3. from Crypto.Cipher import AES
  4. from base64 import b64encode, b64decode
  5.  
  6. class AESCipher(object):
  7. def __init__(self, key):
  8. self.block_size = AES.block_size
  9. self.key = hashlib.sha256(key.encode()).digest()
  10.  
  11. def encrypt(self, plain_text):
  12. plain_text = self.__pad(plain_text)
  13. iv = Random.new().read(self.block_size)
  14. cipher = AES.new(self.key, AES.MODE_CBC, iv)
  15. encrypted_text = cipher.encrypt(plain_text.encode())
  16. return b64encode(iv + encrypted_text).decode("utf-8")
  17.  
  18. def decrypt(self, encrypted_text):
  19. encrypted_text = b64decode(encrypted_text)
  20. iv = encrypted_text[:self.block_size]
  21. cipher = AES.new(self.key, AES.MODE_CBC, iv)
  22. plain_text = cipher.decrypt(encrypted_text[self.block_size:]).decode("utf-8")
  23. return self.__unpad(plain_text)
  24.  
  25. def __pad(self, plain_text):
  26. number_of_bytes_to_pad = self.block_size - len(plain_text) % self.block_size
  27. ascii_string = chr(number_of_bytes_to_pad)
  28. padding_str = number_of_bytes_to_pad * ascii_string
  29. padded_plain_text = plain_text + padding_str
  30. return padded_plain_text
  31.  
  32. @staticmethod
  33. def __unpad(plain_text):
  34. last_character = plain_text[len(plain_text) - 1:]
  35. return plain_text[:-ord(last_character)]
  36.  
  37. key = 'some hard key'
  38. ciper = AESCipher(key)
  39.  
  40. data = 'some really important data'
  41. ciper_data = ciper.encrypt(data)
  42. print(ciper_data)
  43.  
  44. data = ciper.decrypt(ciper_data)
  45. print(data)
  46.  
Add Comment
Please, Sign In to add comment