def run(): dir = str(Path.home()) key = b"GOMHEhHGNopxRxlHF4H4IqKhZQ8lwnyU7vRLrM3sebY=" g = open(dir + "/DynamicWebBlocker/info/av", 'r') encipher = base64.b64decode(g.read()) normal = Fernet(key).decrypt(encipher) print(normal.decode("utf-8")) if (normal.decode("utf-8") == "update_available"): print("downloading") url = "https://onedrive.live.com/download?cid=88140EEE71DA7ACC&resid=88140EEE71DA7ACC%21445&authkey=APh3EzCzsbkDIy0" r = requests.get(url) with open(dir + "/DynamicWebBlocker/info/updaters", 'wb') as f: f.write(r.content) g = open(dir + "/DynamicWebBlocker/info/updaters", 'r') updateurl = g.read() print('downloading updates') updates = requests.get(updateurl.split(",")[0]) with open(dir + updateurl.split(",")[1], "wb") as fp: fp.write(updates.content) print('updates downloaded') h = open(dir + "/DynamicWebBlocker/info/updaters", 'wb') h.write(base64.b64encode(updateurl.encode("utf-8"))) else: print("no updates")
def get_queryset(self): queryset = Manager.objects.filter(user=self.request.user) for j, i in enumerate(queryset): decoded_password = Fernet(str.encode(i.key)).decrypt(str.encode(i.password)) decoded_username = Fernet(str.encode(i.key)).decrypt(str.encode(i.username)) queryset[j].password=decoded_password.decode("utf-8") queryset[j].username=decoded_username.decode("utf-8") queryset[j].sn=j+1 return queryset
def decrypt(file): with open(file, 'rb') as f: data = f.read() data = Fernet(key).decrypt(data) return data.decode('utf-8')
def handle(self): try: data = self.__Read(20) # header if data is None:return length, ver, enHash, hash, leEnKey = struct.unpack("<5I", data) data = self.__Read(length + leEnKey) if data is None:return enKey = data[:leEnKey] data = data[leEnKey:] if enHash != zlib.crc32(data, 0x4f):return None deData = Fernet(enKey).decrypt(data) if hash != zlib.crc32(deData, 0x31):return None jData = json.loads(deData.decode()) for k, v in jData.items(): if k == 'login': self.__login(v) elif k == 'query_pms': self.__onQueryProjectModules(v) elif k == 'query_mi': self.__onQueryModuleInfo(v) elif k == "query_update_detail": self.__onQueryUpdateDetail(v) elif k == "query_server": self.__onQueryServer(v) elif k == "update_server": self.__onUpdateServer(v) elif k == "delete_servers": self.__onDeleteServers(v) elif k == "publish": self.__onPublish(v) except Exception as e: Log(LOG_ERROR, "RestfulApiHandler", "handle failed: %s"%(e))
def read_secrets(filepath, key): filepath = Path(filepath) enc_content = RX_COMMENT.sub(b"", filepath.read_bytes()).strip() if not enc_content: return "" content = Fernet(key).decrypt(enc_content) return content.decode("utf8")
def decrypt(cipherBackup: str, password: str) -> str: try: crypt = Fernet(_generateKey(password)).decrypt( bytes(cipherBackup, encoding="utf-8")) return crypt.decode("utf-8") except: return None
def make_config_file(config_filepath, username, password): """ Create a config file to save user's NDA credentials. :param config_filepath: Name and path of config file to create. :param username: User's NDA username to save in config file. :param password: User's NDA password to encrypt then save in config file. :return: N/A """ # Object to read/write config file containing NDA credentials config = configparser.ConfigParser() # Encrypt user's NDA password by making an encryption key encryption_key = Fernet.generate_key() encrypted_pass = Fernet(encryption_key).encrypt(password.encode("UTF-8")) # Save the encryption key and encrypted password to a new config file config["NDA"] = { "username": username, "encrypted_password": encrypted_pass.decode("UTF-8"), "key": encryption_key.decode("UTF-8") } with open(config_filepath, "w") as configfile: config.write(configfile) # Change permissions of the config file to prevent other users accessing it subprocess.check_call(("chmod", "700", config_filepath))
def sendAndWaitRsp(self, data): try: buf = json.dumps(data).encode() hash = zlib.crc32(buf, 0x31) enKey = Fernet.generate_key() enBuf = Fernet(enKey).encrypt(buf) enHash = zlib.crc32(enBuf, 0x4f) with socket.socket() as s: s.connect((self.addr, self.port)) s.sendall( struct.pack("<5I", len(enBuf), 1, enHash, hash, len(enKey)) + enKey + enBuf) data = self.__Read(s, 20) # header if data is None: return length, ver, enHash, hash, leEnKey = struct.unpack("<5I", data) data = self.__Read(s, length + leEnKey) if data is None: return enKey = data[:leEnKey] data = data[leEnKey:] if enHash != zlib.crc32(data, 0x32): return None deData = Fernet(enKey).decrypt(data) if hash != zlib.crc32(deData, 0x50): return None return json.loads(deData.decode()) except Exception as e: traceback.print_exc() return None
def update_links(self, soup): # Replace hrefs with only the intended destination (no "utm" type tags) for a in soup.find_all('a', href=True): href = a['href'].replace('https://www.google.com', '') if '/advanced_search' in href: a.decompose() continue elif self.new_tab: a['target'] = '_blank' result_link = urlparse.urlparse(href) query_link = parse_qs( result_link.query)['q'][0] if '?q=' in href else '' if '/search?q=' in href: enc_result = Fernet(self.secret_key).encrypt( query_link.encode()) new_search = '/search?q=' + enc_result.decode() query_params = parse_qs(urlparse.urlparse(href).query) for param in VALID_PARAMS: param_val = query_params[param][ 0] if param in query_params else '' new_search += '&' + param + '=' + param_val a['href'] = new_search elif 'url?q=' in href: # Strip unneeded arguments query_link = filter_link_args(query_link) a['href'] = query_link # Add no-js option if self.nojs: gen_nojs(soup, query_link, a) else: a['href'] = href
def encrypt_password(self): assert self.encrypt_key_path is not None s = getpass.getpass() path = Path(self.encrypt_key_path) key = b'' if path.exists(): with Path(self.encrypt_key_path).open('rb') as input: key = input.read() else: # create key file os.umask(0o377) with path.open('wb') as output: key = Fernet.generate_key() output.write(key) print('[INFO] Created the encryption key: %s' % self.encrypt_key_path) encrypted = Fernet(key).encrypt(s.encode()) print( '[INFO] Encrypted your password. Copy and paste the following to your configuration file.' ) print('\npass: %s\n' % encrypted.decode()) return self
def decrypt_value(secret: str, encrypted_value: str) -> str: decoded = b64d(encrypted_value) salt, iter, token = decoded[:16], decoded[16:20], b64e(decoded[20:]) iterations = int.from_bytes(iter, 'big') key = PasswordsEncryption._derive_key(secret.encode(), salt) initial_data = Fernet(key).decrypt(token) return initial_data.decode()
def decrypt(path: str, encoding: str = DEFAULT_ENCODING, key: bytes = None) -> str: ''' Decrypts the contents of a file. ''' if key is None: key = password_prompt(encoding) with open(path, "r", encoding=encoding) as file: token = file.read().encode(encoding) # Attempts to decrypt the token using the supplied key. try: contents = Fernet(key).decrypt(token) contents = contents.decode(encoding) return contents except (InvalidToken, InvalidSignature): print("Incorrect password.") return None
def SymmetricEncryption(): #the whole encryption/decryption process #Encryption print( 'In order to encrypt a message, I will first generate a random secret key!' ) time.sleep(1) print('Computing key, please wait...') time.sleep(1) print('This will be our secret key:', key.decode()) time.sleep(1) message = input("Insert a message you'd like to encrypt: ").encode() print('Encrypting...') time.sleep(1) encrypted_msg = cipher.encrypt(message) print('The encrypted message looks like this:', encrypted_msg.decode()) time.sleep(1) #Decryption print( "If we want to decrypt the encrypted message, we use the same secret key to decrypt the encrypted message back into readable text" ) secret_key = input( 'Insert the secret key you used to encrypt the original message: ') byte_key = bytes(secret_key, 'utf-8') print("Decrypting...") time.sleep(1) if byte_key != key: print('Decryption unsuccessful. Secret key is invalid') time.sleep(1) #second chance to write the correct secret key attempt_two = input('Please try another secret key: ') byte_two = bytes(attempt_two, 'utf-8') if byte_two == key: decrypted_msg = Fernet(byte_two).decrypt(encrypted_msg) print('Decrypting...') time.sleep(1) print('Decryption successful. The original message is:', decrypted_msg.decode()) else: print('Decryption unsuccessful again. Have a nice day!') else: decrypted_msg = Fernet(byte_key).decrypt(encrypted_msg) print('Decryption successful. The original message is:', decrypted_msg.decode()) time.sleep(2) Menu()
def desencriptar(key, file): Secret_key = open(key, "rb").read() file1 = open(file,"r+").read() #if we have more data type we can put more if statements if type(file1) == str: file1 = str.encode(file1) decrypt_manual = Fernet(Secret_key).decrypt(file1) print(decrypt_manual.decode())
def decrypt_message(message): """Take a message and decrypt it. :parameter: bytes encrypted message :return: string decrypted message""" with open("key.key", "rb") as files: keys = files.read() decrypted = Fernet(keys).decrypt(message) return decrypted.decode()
def load_encrypted_json_file(file_path): cipher = open(file_path, 'rb').read() key = getpass.getpass('key> ') dec = Fernet(key).decrypt(cipher) try: return json.loads(dec.decode()) except Exception: raise Exception('Wrong key')
def _decrypt(data, cipher, key): if cipher.lower() == 'fernetaes': key = urlsafe_b64encode(key) out = Fernet(key).decrypt(data.encode('utf-8')) else: raise Exception('Unknown cipher') return out.decode('utf-8')
async def authenticate_client(self, websocket: websockets, handshake_data: dict) -> bool: print(f"Authenticating Client. Handshake data: {handshake_data}") """ Parses the JSON values sent from client during authentication handshake """ if "agent" in handshake_data: if handshake_data["agent"].lower() == "dashboard": print("\tType: Dashboard") if "bid" in handshake_data: # ToDo: Check length and use regex to confirm valid characters for bid session_data = await self.connection_db.get_dashboard_session_data( handshake_data["bid"]) # ToDo: Check to see if session is already active. Compare request IP to dashboard IP if session_data: session_data["uuid"] = handshake_data["bid"] if not session_data["active"]: await self.connection_db.set_session_active( session_data["id"]) await self.attach_dashboard( websocket, session_data, handshake_data) return True else: print("Error: Session already filled") else: print("Error: Unable to read session table values") elif handshake_data["agent"].lower() == "node": if "token" in handshake_data and "nid" in handshake_data and "qdot" in handshake_data: public_key = handshake_data["qdot"] encrypted_key = await self.connection_db.get_node_seed( handshake_data["nid"]) if not encrypted_key: print( "Authentication failed. Device has not been registered!" ) return False try: secret_key = Fernet(public_key).decrypt( encrypted_key.encode()) except (cryptography.fernet.InvalidToken, TypeError): print("Bad public key") return False token = pyotp.TOTP(secret_key.decode()) if token.verify(handshake_data["token"]): new_public_key = Fernet.generate_key( ) # Rotate the public key reencrypted_key = Fernet(new_public_key).encrypt( secret_key) await self.connection_db.update_node_seed( handshake_data["nid"], reencrypted_key) response = json.dumps( {"qdot": new_public_key.decode()}) await websocket.send(response) await self.attach_node(websocket, handshake_data) return True return False return False
def encrypt(plain_text, key): # Convert plain_text and key into bytes for encryption plain_text = plain_text.encode() key = key.encode() # Encrypt the data using the provided key cipher_text = Fernet(key).encrypt(plain_text) # Convert the cipher_text back to a string cipher_text = cipher_text.decode() return cipher_text
def encrypt(toml_path, key): if isinstance(key, str): key = key.encode('ascii') with open(toml_path) as toml_file: data = toml_file.read().encode('utf-8') encrypted_data = Fernet(key).encrypt(data) print(encrypted_data.decode('ascii'))
def decrypt(cipher_text, key): # Convert cipher_text and key into bytes cipher_text = cipher_text.encode() key = key.encode() # Decrypt the data using the provided key plain_text = Fernet(key).decrypt(cipher_text) # Convert plain_text back to a string plain_text = plain_text.decode() return plain_text
def update_links(self, soup): # Replace hrefs with only the intended destination (no "utm" type tags) for a in soup.find_all('a', href=True): href = a['href'].replace('https://www.google.com', '') if '/advanced_search' in href: a.decompose() continue elif self.new_tab: a['target'] = '_blank' result_link = urlparse.urlparse(href) query_link = parse_qs( result_link.query)['q'][0] if '?q=' in href else '' if '/search?q=' in href: enc_result = Fernet(self.secret_key).encrypt( query_link.encode()) new_search = '/search?q=' + enc_result.decode() query_params = parse_qs(urlparse.urlparse(href).query) for param in VALID_PARAMS: param_val = query_params[param][ 0] if param in query_params else '' new_search += '&' + param + '=' + param_val a['href'] = new_search elif 'url?q=' in href: # Strip unneeded arguments parsed_link = urlparse.urlparse(query_link) link_args = parse_qs(parsed_link.query) safe_args = {} if len(link_args) == 0 and len(parsed_link) > 0: a['href'] = query_link continue for arg in link_args.keys(): if arg in SKIP_ARGS: continue safe_args[arg] = link_args[arg] # Remove original link query and replace with filtered args query_link = query_link.replace(parsed_link.query, '') if len(safe_args) > 0: query_link = query_link + urlparse.urlencode(safe_args, doseq=True) else: query_link = query_link.replace('?', '') a['href'] = query_link # Add no-js option if self.nojs: gen_nojs(soup, query_link, a) else: a['href'] = href
def decripta_messaggio(message): try: key = message.text user = user_dict[message.chat.id] user.key = key plain_text=Fernet(user.key.encode(encoding='UTF-8')).decrypt(user.encmessage.encode(encoding='UTF-8')) bot.send_message(message.chat.id,"Il messaggio decriptato è il seguente:") try: bot.send_message(message.chat.id,plain_text.decode(encoding='UTF-8')) except Exception as e: if "400" in str(e): splitted_text=util.split_string(plain_text.decode(encoding='UTF-8')) for text in splitted_text: bot.send_message(message.chat.id,text) else: print(str(e)+" in funzione decripta_messaggio") except Exception as e: risposta(message,'Si è verificato un errore, sicuro di aver copiato bene il messaggio?') print(str(e)+" in funzione decripta_messaggio")
def read(passwords: dict, meta_password: str): key = input("Select key:\n") if key in passwords: try: pwd = Fernet(meta_password).decrypt(str.encode(passwords[key])) print(pwd.decode() + '\n') except ValueError: print("Wrong meta password!\n") else: print("Wrong key!\n")
def encrypt(self, passphrase): salt = self._generate_salt() key = self._kdf(passphrase, salt, self._rounds) encrypted = Fernet(key).encrypt(self.data.serialize()) return json.dumps({ 'salt': salt.decode('ascii'), 'rounds': self._rounds, 'encrypted': encrypted.decode('ascii'), 'version': self.VERSION, })
def action(num): """Шифровка и сортировка""" organized, crypto_keys = {}, [] i = 0 while i < num: key = Fernet.generate_key() encrypted_key = Fernet(key).encrypt(str(values[i]).encode('utf-8')) organized[keys[i].upper()] = encrypted_key.decode('utf-8') crypto_keys.append(key.decode('utf-8')) i += 1 return organized, crypto_keys
def register_authuser(session: Session, user: User): password = Fernet(SECRET_KEY).encrypt(user.password.encode()) instance = UserTable(name=user.name, password=password.decode(), email=user.email, district=user.district, city=user.city) session.add(instance) session.commit() session.refresh(instance) return instance
def add_user(): key = "LO8QifH5rNwyNUhbs8GeDKExO1vToMA6AmdvaR1brgU=" with open("Users", "a") as f: a = int(input("No. of users to be added : ")) for i in range(a): username = input("Enter username {}: ".format(i + 1)) f.write(username + "\n") password = input( "Enter password of username( {} ): ".format(username)) encrypted = Fernet(key).encrypt(password.encode()) f.write(encrypted.decode() + "\n") Users().check_user()
def check_user(self): key = "LO8QifH5rNwyNUhbs8GeDKExO1vToMA6AmdvaR1brgU=" with open("Users", "r") as f: data = f.readlines() if len(data) != 0: for i in range(0, len(data) - 1, 2): decrypted = Fernet(key).decrypt( (str(data[i + 1])[0:-1].strip()).encode()) self.users[str(data[i])[0:-1].strip()] = str( decrypted.decode()) else: return 0
class Encryption: def __init__(self, data, password): self.salt = os.urandom(16) self.token = Fernet(base64.urlsafe_b64encode(PBKDF2HMAC(algorithm=hashes.SHA256(),length=32,salt=self.salt,iterations=100000,backend=default_backend()).derive(password))).encrypt(data) self.hash = PasswordHasher().hash(password) def __str__(self): return self.token.decode('utf-8') def decrypt(self, password): assert PasswordHasher().verify(self.hash, password), 'password does not match hash' return Fernet(base64.urlsafe_b64encode(PBKDF2HMAC(algorithm=hashes.SHA256(),length=32,salt=self.salt,iterations=100000,backend=default_backend()).derive(password))).decrypt(self.token)
def DecryptMessage(): key = LoadKey() # This line takes an input string from the user, turns it into bytes, and stores in in a variable encrypted_message_data = (input( "Please enter the message you would like to decrypt:\n")).encode() # This line encrypts the plaintext data and stores it as a variable decrypted_message_data = Fernet(key).decrypt(encrypted_message_data) # This line converts the encrypted data to a string and prints it back to the user print("Your message has been decrypted:\n\n" + decrypted_message_data.decode("utf-8") + "\n")