def userConnection(self): global Users try: while True: with socket.socket( socket.AF_INET, socket.SOCK_STREAM ) as s: # Run socket to receive messages from user on their ports s.bind((HOST, self.RequestPORT)) s.listen(1) conn, addr = s.accept() with conn: data = conn.recv(2048) text = str(data.decode( "utf-8")) # decode received from bytes to string f = Fernet(base64.urlsafe_b64encode(self.derived_key) ) # decrypt message using the user's key text = f.decrypt(data).decode("utf-8") if "Authenticate" in text: #User wants to authenticate. Let's see if they are legit result, self.user = checkUser(self) if (result): self.authenticated = True if self.user not in Users: Users.append( self.user ) # If this isn't a duplicate, add them to the users list if "Send USB" in text and self.authenticated: # User needs to verify their device serial number SNs = receiveAndDecrypt(HOST, self.ClientToServerPORT, self.derived_key) self.verifiedUSB = checkSNMatch(self, SNs, adminKey) if (self.verifiedUSB): self.files, self.keys = readFileDB( self.user + 'files.txt', self.user + 'keys.txt.enc', adminKey) # Send number of files this user manages and then each file name sendEncryptedData(str(len(self.files)), HOST, self.ServerToClientPORT, self.derived_key) for i in self.files: sendEncryptedData(str(i), HOST, self.ServerToClientPORT, self.derived_key) if "Decrypt Request" in text and self.authenticated: # User wants to decrypt some files if (self.verifiedUSB): self.files, self.keys = readFileDB( self.user + 'files.txt', self.user + 'keys.txt.enc', adminKey) receiveDecryptionRequest(self, HOST) else: print( "User not authenticated but they tried to decrypt files" ) if "Remove Files" in text and self.authenticated: # User wants to remove some files from being tracked numFiles = int( receiveAndDecrypt( HOST, self.ClientToServerPORT, self.derived_key).decode("utf-8")) for i in range(numFiles): file = receiveAndDecrypt( HOST, self.ClientToServerPORT, self.derived_key).decode("utf-8") if file in self.files: idx = self.files.index(file) del self.files[idx] del self.keys[idx] updateFileDB(self.files, self.keys, self.user, adminKey) else: print("File not found: ", file) if "Encrypt" in text and self.authenticated: # User wants to encrypt some files if (self.verifiedUSB): # print("Received Encryption Message") newFiles, newKeys = receiveEncryptionRequest( HOST, self.ClientToServerPORT, self.ServerToClientPORT, self.derived_key) for i in range(len(newFiles)): try: idx = self.files.index(newFiles[i]) self.keys[idx] = newKeys[i] except ValueError: self.files.append(newFiles[i]) self.keys.append(newKeys[i]) updateFileDB(self.files, self.keys, self.user, adminKey) else: print( "User not authenticated but they tried to encrypt files" ) if "changePW" in text and self.authenticated: #User wants to change their password. This is handled in the GUI thread so add messages to queues toGUIQueue.put("changePW") toGUIQueue.put(self.user) toGUIQueue.put(self) except KeyboardInterrupt: return
def encrypt_sym(key, data): """ Encrypt the given data with the given key. """ f = Fernet(key) return f.encrypt(data)
if len(final_bin) != 16: # print("Printing the postion values from the split\n",final_bin,"\n\n\n") final_bin = final_bin + "0" # AES_Decryption filename1 = "encrypt.txt" f = open(filename1, "r") temp1 = f.read().replace('\n', '') f.close() token1 = str.encode(temp1) # String converted back to bytes # Key_file fill = open("key.txt", "r") temp2 = fill.read().replace('\n', '') fill.close() key = temp2 f = Fernet(key) token2 = f.decrypt(token1) # print("token2:",token2) # Converting token2 to string for comparing#print("\n\nhash_temp :",hash_temp) hash_temp = token2.decode() if hash2 == hash_temp: count = count + 1 # Authentication_1 # Pattern_file file1 = open('pattern.txt', 'r') Lines = file1.readlines() ip = final_bin time.sleep(4) fin = time.time() temps = fin - start timer_timer = temps #print("runtime is:",temps)
def decrypt(data, key): f = Fernet(key) return f.decrypt(data)
root.withdraw() mbox.showerror("ERROR", "Image could not be found") raise SystemExit else: # Run GUI code # reads the encryption key keyfile = open('key.key', 'rb') # open the file as wb to read bytes key = keyfile.read() # the key will be type bytes # decrypts the image eFormat_file = 'Format.encrypted' Format_file = 'Format.PNG' with open(eFormat_file, 'rb') as f: data = f.read() # read the bytes of the encrypted image fernet = Fernet(key) try: decrypted = fernet.decrypt(data) with open(Format_file, 'wb') as f: f.write(decrypted) # write the decrypted bytes to the output file except InvalidToken as e: # error window execution root.withdraw() mbox.showerror("ERROR", "An ERROR has occured please reinstall the program") raise SystemExit # decrypts the image eBackground_file = 'Background.encrypted'
def _encrypt_bytes(bytes_value: bytes) -> bytes: """Encrypt bytes with Fernet.""" return Fernet(get_app_var(3)).encrypt(bytes_value)
def _decrypt_bytes(bytes_value): """Decrypt bytes with Fernet.""" try: return Fernet(get_app_var(3)).decrypt(bytes_value) except (InvalidToken, AttributeError): return None
def chekpass(pswd): try: suit = Fernet(pswd) return True except: return False
def __init__(self, pswd): self.suit = Fernet(pswd)
print(key, ' : ', value) def command(): global f f = str(input("Command: ")) return f bruh = True v = {} while bruh == True: key_infile = open('dubdub.pkl', 'rb') key = pickle.load(key_infile) key = Fernet(key) command() if f == "n": website = str(input("Website: ")) username = "******" + input("Username: "******"******" + input("Password: "******"a": allpass() if f == "k": del_website = input("Which Saved Password do You want to Delete?: ") deletepass(del_website, v) if f == "end": bruh = False print("You have ended your storage session.")
ip = '127.0.0.1' print("What is port number of this Client server? : ") my_port = int(input()) print("What is port number of Key Distribution Server? : ") kdsp = int(input()) kds = ('127.0.0.1', kdsp) my_addr = ('127.0.0.1', my_port) client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) client.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) client.bind(my_addr) keys = {} my_info = pickle.dumps(my_port) client.sendto(my_info, kds) message = client.recvfrom(4096) keys['kds'] = Fernet(message[0]) client_numb = client.recvfrom(4096) client_numb = int(client_numb[0].decode()) file_server_info = client.recvfrom(4096) file_server_info = str(file_server_info[0].decode()) print(file_server_info) if (client_numb == 1): client_name = 'cs1' elif (client_numb == 2): client_name = 'cs2' elif (client_numb == 3): client_name = 'cs3' #once info sent client wants to access file server
def decrypt(message): encoded = message.encode() f = Fernet(key) decrypted = f.decrypt(encoded) return decrypted.decode()
def encrypt(message): encoded = message.encode() # Changing format to be in bytes. f = Fernet(key) encrypted = f.encrypt(encoded) return encrypted.decode()
def fernet(self, key): _key = key + "=" * (len(key) % 4) _key = base64.urlsafe_b64encode(base64.urlsafe_b64decode(_key)) return Fernet(_key)
from .telegram import TG from .db_utils import * # SendGrid API Key SENDGRID_API_KEY = config('SENDGRID_API_KEY') # Initialize object for sending messages to telegram tg = TG(config('BOT_API_KEY', default=None)) # Retrieve ID of Telegram log channel log_channel = config('LOG_ID', default=None) # Create fernet object using secret key fernet = Fernet(config('FERNET_KEY')) DATABASE_CLASSES = { 'codex_april_2019': CodexApril2019, 'eh_july_2019': EHJuly2019, 'cpp_workshop_may_2019': CPPWSMay2019, 'rsc_2019': RSC2019, 'c_cpp_workshop_august_2019': CCPPWSAugust2019, 'do_hacktoberfest_2019': Hacktoberfest2019, 'csi_november_2019': CSINovember2019, 'csi_november_non_member_2019': CSINovemberNonMember2019, 'p5_november_2019': P5November2019, 'c_november_2019': CNovember2019, 'bitgrit_december_2019': BitgritDecember2019, 'test_users': TestTable, 'access': Access,
from cryptography.fernet import Fernet key = Fernet.generate_key() cipher_suite = Fernet(key) cipher_text = cipher_suite.encrypt( b"A really secret message. Not for prying eyes.") print(cipher_text) plain_text = cipher_suite.decrypt(cipher_text) print(plain_text)
def _encrypt_string(str_value: str) -> str: """Encrypt a string with Fernet.""" return Fernet(get_app_var(3)).encrypt(str_value.encode()).decode()
def encrypt(message: bytes, key: bytes) -> bytes: return Fernet(key).encrypt(message)
def _decrypt_string(encrypted_str: str) -> str: """Decrypt a string with Fernet.""" try: return Fernet(get_app_var(3)).decrypt(encrypted_str.encode()).decode() except (InvalidToken, AttributeError): return None
def decrypt(token: bytes, key: bytes) -> bytes: return Fernet(key).decrypt(token)
def main(): f = Fernet(key) print(f.decrypt(message))
+---------------------------+ | UNIP | APS - Criptografia | | Yuri Almeida - F224EA7 | | Julio Perozzi - F12IDA4 | +---------------------------+ """) #Encriptação if click.confirm('Voce deseja encriptar a mensagem?', default=True): msg_argv = input("Digite sua mensagem: ") key = Fernet.generate_key() # geração da chave_secreta! print(type(key)) print(b'sua chave secreta:',key) # imprime chave_secreta! time.sleep(2) #aguarda 2s print("Aguarde estamos encriptando...") time.sleep(2) #aguarda 2s encrypt_msg = Fernet(key) #valor da chave_secreta é atribuído a uma variável->encrypt_msg encrypted_msg = encrypt_msg.encrypt(msg_argv.encode()) # encripta mensagem do usuario! print("sua string: ",encrypted_msg) #imprime string//texto_encriptado! #Decriptação if click.confirm('Voce deseja decriptar sua string?', default=True): msg_argv2 = input("Sua string: ") # entrada da string//texto_encriptado! time.sleep(1.25) #aguarda 1.25s secret = input("Sua chave secreta: ") # entrada da chave secreta! print(type(secret)) print(secret) print("[!]decriptando a sua mensagem secreta..[!]") time.sleep(2) #aguarda 2s print("[+]mensagem decriptada com sucesso[+]") time.sleep(2.25) #aguarda 2.25s decrypt_msg = Fernet(secret) #valor chave_secrete é atribuído a uma variável->decrypt_msg
def encrypt(data, key): f = Fernet(key) return f.encrypt(data)
def __init__(self, event): self.event = event self.params = self.__get_parameters() self.cipher_suite = Fernet(SECRET_KEY)
def decrypt_sym(key, data): """ Decrypt the given data with the given key. """ f = Fernet(key) return f.decrypt(data)
def __init__(self, k): #create a Fernet object self.f = Fernet(k)
pos += 1 items = items_collection.find( {"title": { "$regex": regex, "$options": 'i' }}) print('\nAfter deleting the item') print_title(items) # Main Function if __name__ == "__main__": file = open('encrption_key.key', 'rb') encryption_key = file.read() fernet_key = Fernet(encryption_key) file.close() client = MongoClient("mongodb://<server>/<dbname>") #database db = client.testDB #collection name items_collection = db.coll print("WELCOME TO THE ADMIN INVENTORY SECTION!!") # Add, update, delete product admin_name = input('\nEnter username: '******'Enter Password: ') is_valid, username = auth_user(admin_name, password, db.admin_table, fernet_key) if is_valid:
def encrypt(): key = Fernet.generate_key().decode("ascii") cipher_suite = Fernet(key) drives = win32api.GetLogicalDriveStrings() drives = drives.split("\000")[:-1] l1 = [ ".jpg", ".jpeg", ".csv", ".png", ".db", ".doc", ".mpeg", "mpeg4", ".avi", ".docx" ] for d in drives: for dirpath, dirs, files in os.walk(d): print("Encrypting... {}".format(dirpath)) try: for filename in files: f = "{}\\{}".format(dirpath, filename) if os.path.splitext(str(f))[-1] == ".txt": with open(f, 'r') as txt: files_txt = txt.read() if not files_txt.startswith("gAAAAA"): cipher_text = cipher_suite.encrypt( bytes(files_txt.encode("utf-8"))).decode( "ascii") with open(f, 'w') as txt_enc: txt_enc.write(cipher_text) elif os.path.splitext(str(f))[-1] == ".pdf": pdf = PdfFileReader(open(f, "rb"), strict=True) if not pdf.isEncrypted: path_pdf, f_pdf = os.path.split(f) output_file = os.path.join( path_pdf, "enc_{}".format(filename)) output = PdfFileWriter() input_stream = PdfFileReader(open(f, "rb")) for i in range(0, input_stream.getNumPages()): output.addPage(input_stream.getPage(i)) output_stream = open(output_file, "wb") output.encrypt(user_pwd=key, owner_pwd="test", use_128bit=True) output.write(output_stream) input_stream.stream.close() output_stream.close() pdf.stream.close() os.remove(f) pdf.stream.close() elif os.path.splitext(str(f))[-1] in l1: with open(f, "rb") as others: c = zlib.compress(others.read(), 9) path_files, f_others = os.path.split(f) output_file2 = os.path.join(path_files, "enc_{}".format(filename)) with open(output_file2, "wb") as o: o.write(c) others.close() o.close() os.remove(f) else: continue except Exception as e: print(e) time.sleep(10) continue
def encrypt_by_key(message, key): f = Fernet(key) return f.encrypt(message)
def __init__(self): self.key = self.prepareKey() self.fernet = Fernet(self.key)