Guest User

Python Encrypt/Decrypt witht bcrypt

a guest
Apr 24th, 2018
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.35 KB | None | 0 0
  1. import requests
  2. from Crypto import Random
  3. from Crypto.Cipher import AES
  4. import base64
  5.  
  6. class Toolbox():
  7.     def __init__(self):
  8.         """
  9.            Provides peripheral & reusable functions for the app
  10.        """
  11.         self.ENCRYPTION_KEY = '40c8c33c-6733-4244-bdd8-e118e0e8'.encode()
  12.  
  13.     def encrypt( self, raw_text ):
  14.         """
  15.            Encrypts a string using bcrypt algorithm
  16.            @raw_text is data to be encrypted
  17.            returns bcrypt encrypted text
  18.        """
  19.         # - AES requires its bnlocks to be of size mod 16
  20.         # - However we don't want unusable characters in a password
  21.         # - First Pipe "|" delimits the end of the password
  22.         if len(raw_text)%16 != 0:
  23.             raw_text = raw_text+"|"
  24.         # - Then Tilde "~" acts as padding.
  25.         while len(raw_text)%16 != 0:
  26.             raw_text = raw_text+"~"
  27.         raw_text = raw_text.encode()
  28.         # Generate a new random block
  29.         random_block = Random.new().read( AES.block_size )
  30.         # Encrypt plain text with a key and hash
  31.         cipher = AES.new( self.ENCRYPTION_KEY, AES.MODE_CBC, random_block )
  32.         text_cipher = cipher.encrypt( raw_text )
  33.         block_and_cipher = random_block + text_cipher
  34.         b64_cipher = base64.b64encode( block_and_cipher )
  35.         return b64_cipher
  36.  
  37.     def decrypt( self, encrypted_text ):
  38.         """
  39.            Decrypts into text using bcrypt algorithm
  40.            @encrypted_text:Input is a bcrypt encrypted block
  41.            returns raw text
  42.        """
  43.         encrypted_text = base64.b64decode(encrypted_text)
  44.         iv = encrypted_text[:16]
  45.         try:
  46.             cipher = AES.new(self.ENCRYPTION_KEY, AES.MODE_CBC, iv )
  47.         except:
  48.             self.cleanPrint("Decryption error","error")
  49.             return
  50.  
  51.         # - To compensate for delimeter/padding above, we rstrip
  52.         # - the excess & remove the padding
  53.         decrypt_msg = cipher.decrypt(encrypted_text[16:])
  54.         decrypt_msg = decrypt_msg.decode()
  55.         decrypt_msg = decrypt_msg.rstrip("~")
  56.         decrypt_msg = decrypt_msg.rstrip("|")
  57.         return decrypt_msg
  58.  
  59. def main():
  60.     tlbx = Toolbox()
  61.     raw_String = "how now brown cow"
  62.     print(raw_String)
  63.     enc = tlbx.encrypt(raw_String)
  64.     print(enc)
  65.     dec = tlbx.decrypt(enc)
  66.     print(dec)
  67.  
  68. if __name__ == '__main__':
  69.     main()
Advertisement
Add Comment
Please, Sign In to add comment