def DPLogin(request): if request.method == "POST": data = json.loads(request.body) if data["select"] == "Patient": query = PatientRegister.objects.all().filter( email=data["email"]).first() if (query and cryptocode.decrypt(query.password, encrypt_key) # noqa == data["password"] # noqa ): token = cryptocode.encrypt(str(query.id), token_key) user = { "id": query.id, "name": query.name, "email": query.email, "login_type": "patient", } return JsonResponse({ "token": token, "user": user, "msg": "Patient login successful" }) else: return HttpResponse("Invalid Credentials", status=404) elif data["select"] == "Doctor": query = DoctorRegister.objects.all().filter( email=data["email"]).first() if (query and cryptocode.decrypt(query.password, encrypt_key) # noqa == data["password"] # noqa ): token = cryptocode.encrypt(str(query.id), token_key) user = { "id": query.id, "name": query.name, "email": query.email, "login_type": "doctor", } return JsonResponse({ "token": token, "user": user, "msg": "Doctor login successful" }) else: return HttpResponse("Invalid Credentials", status=404) else: return HttpResponse("bad request", status=404) else: return HttpResponse("bad request", status=404)
def test_get_items(self): passkey = environ.get('REPO_ACCESS_TOKEN') username = environ.get("TGTG_USERNAME", None) env_file = environ.get('GITHUB_ENV', None) timeout = environ.get('TGTG_TIMEOUT', 60) if passkey: encrypted_access_token = environ.get("TGTG_ACCESS_TOKEN", None) encrypted_refresh_token = environ.get("TGTG_REFRESH_TOKEN", None) encrypted_user_id = environ.get("TGTG_USER_ID", None) access_token = cryptocode.decrypt( encrypted_access_token, passkey) if encrypted_access_token else None refresh_token = cryptocode.decrypt( encrypted_refresh_token, passkey) if encrypted_refresh_token else None user_id = cryptocode.decrypt( encrypted_user_id, passkey) if encrypted_user_id else None else: access_token = environ.get("TGTG_ACCESS_TOKEN", None) refresh_token = environ.get("TGTG_REFRESH_TOKEN", None) user_id = environ.get("TGTG_USER_ID", None) client = TgtgClient( email=username, timeout=timeout, access_token=access_token, refresh_token=refresh_token, user_id=user_id, ) # get credentials and safe tokens to GITHUB_ENV file # this enables github workflow to reuse the access_token on sheduled runs # the credentials are encrypted with the REPO_ACCESS_TOKEN credentials = client.get_credentials() if env_file: with open(env_file, "a") as file: file.write("TGTG_ACCESS_TOKEN={}\n".format( cryptocode.encrypt(credentials["access_token"], passkey))) file.write("TGTG_REFRESH_TOKEN={}\n".format( cryptocode.encrypt(credentials["refresh_token"], passkey))) file.write("TGTG_USER_ID={}\n".format( cryptocode.encrypt(credentials["user_id"], passkey))) # Tests data = client.get_items(favorites_only=True) assert len(data) > 0 for prop in GLOBAL_PROPERTIES: assert prop in data[0] for prop in ITEM_PROPERTIES: assert prop in data[0]["item"] for prop in PRICE_PROPERTIES: assert prop in data[0]["item"]["price_including_taxes"]
def DPLogin(request): if request.method == 'POST': data = json.loads(request.body) if data['select'] == 'Patient': query = PatientRegister.objects.all().filter(email=data['email']).first() if query and cryptocode.decrypt(query.password,encrypt_key ) == data['password']: token = cryptocode.encrypt(str(query.id),token_key) user = { 'id':query.id, 'name':query.name, 'email':query.email, 'login_type':'patient' } return JsonResponse( { 'token':token, 'user':user, 'msg':'Patient login successful' }) else: return HttpResponse('Invalid Credentials',status=404) elif data['select'] == 'Doctor': query = DoctorRegister.objects.all().filter(email=data['email']).first() if query and cryptocode.decrypt(query.password,encrypt_key ) == data['password']: token = cryptocode.encrypt(str(query.id),token_key) user = { 'id':query.id, 'name':query.name, 'email':query.email, 'login_type':'doctor' } return JsonResponse( { 'token':token, 'user':user, 'msg':'Doctor login successful' }) else: return HttpResponse('Invalid Credentials',status=404) else: return HttpResponse('bad request',status=404) else: return HttpResponse('bad request',status=404)
def addOutputFunc(newOut, reciever, amount): global outputs global password global currentTx newOut.destroy() outputs.append([reciever, int(float(amount) * 1000000000)]) with open("wallet.dat", "r") as wallet: data = json.loads(wallet.read()) public = data["publicHex"] private = cryptocode.decrypt(data["privateHex"], password) #reading and updating nonce nonce = data["nonce"] with open("wallet.dat", "w") as walletWrite: data["nonce"] += 1 walletWrite.write(json.dumps(data)) currentTx = transaction(public, reciever, int(float(amount) * 1000000000), time.time(), private, nonce) for x in outputs: if not x in currentTx.outputs: currentTx.addOutput(x) txAmountLabel.config( text="Total(+Fee): " + str((calculateFee(currentTx) + currentTx.txamount) / 1000000000)) txFeeLabel.config(text="Estimated Fee: " + str(calculateFee(currentTx) / 1000000000))
def set_sub_cipher(self): """ arg: str(workout_id) :return: """ key = ds_client.key('cybergym-workout', self.workout_id) workout = ds_client.get(key) # TODO: Randomly select message from list of messages message = "a/0TTGJzT7y6GncKO+bXA82HlWXbhyRf3O2tRtqMG+xq/zncd5aXG/Ku9vwsA4cXJzZN7aT7Qi" \ "1QAqUTQ9LNRlGfhw6noVXCVgLVKnoHX2E4p3TU4buuDNAhwsmBCjaPydmVDbXznR8BCeqtc7rb" \ "1WDB9DM/L8mKi+rJ2IyK3tubrh5lQxoicJaFTS3/3uNbdoF5oAQwK9qXLrCDFSeEuxH9x6fLx/" \ "jw1VPdZyiaMBqhCKJzIxXXrk1x3AjzsGHes4PN2HmwLHTPabatjpdc+7++HoX0WYS3uFDtlnqq" \ "/30VCtHVhj7/9/5G8kM+2SCr9uVnOFoUVac2k8lA9S654LJ/SvNxoJIAnnN8kmRB3hTHUy+hLz" \ "INSCi94HXzRKegF6l2cqDzIzax3AkEvMEDrnr9SyKl4kPbJUhpS9rsIHSR4VZ+ftTl6OyQyYcU" \ "8PISQ3LbMDlab3kRLQMyQLUE6P1W3dSb2d0E8FMzNJRVZG8qni31EJDdhEE1XoeN5KNuOqHlUg" \ "YnEQTnnnZQO7cpZHbJkig+*rMa79jvw3ZAdCPVmTXHlWg==*dr8W9+jtjlpUMx3aXteeQw==*O" \ "yOuE5XXG9jLU2HwvJchNw==" decrypt_key = workout['assessment']['key'] plaintext = cryptocode.decrypt(message, decrypt_key) cipher = substitution_encrypt(plaintext) # Put cipher in datastore object workout['container_info']['sub_cipher']['cipher'] = cipher['ciphertext'] workout['container_info']['sub_cipher']['cleartext'] = cipher['cleartext'] workout['container_info']['sub_cipher']['key'] = cipher['key'] ds_client.put(workout) status = workout['assessment']['questions'][3]['complete'] data = { 'cipher': cipher['ciphertext'], 'status': status, } return data
def Decrypt(self): text = self.TextEntry.get() key = self.KeyEntry.get() result = cryptocode.decrypt(text, key) self.ResultEntry.config(state="normal") self.ResultEntry.delete(0, tk.END) self.ResultEntry.insert(0, result)
def decode(self): text = self.dectext.toPlainText() password = self.decpass.toPlainText() decoded = cryptocode.decrypt(text, password) if decoded == False: self.decoutput.setText("wrong password or text") else: self.decoutput.setText(decoded)
def addleavetomfunc(): user = leaveusername.get() mainuser = entry1.get() with open("userpassdata","r") as f: for line in f: lst = line lst = lst.replace("'","") lst = lst.replace(" ","") lst= lst.strip("[] \n") ls = lst.split(",") userdata = [] if ls != ['!!confidential!!']: usern = decrypt(ls[0],ls[2]) userp = decrypt(ls[1],ls[2]) userdata = [usern, userp, ls[2]] if userdata[0] == user: with open("usersprivate","r") as f: for line2 in f: if user in line2: uun = line2.split(",") uun.pop(-1) un = "" un = un.join(uun) f.close() break with open("usersprivate","r") as f: for line2 in f: if mainuser in line2: uun = line2.split(",") uun.pop(-1) un2 = "" un2 = un2.join(uun) f.close() break with open("Leaves","a") as f: f.write("\n") f.write("\n") dtime2 = dtime.split(" ") dtime2 = dtime2[0] f.write(dtime2) f.write("\n") wr = un +" "+"On Leave Tomorrow"+" "+"Added By" +" "+ un2 f.write(str(wr)) f.close() win.destroy() return
def checkuser(): user = entry1.get() password = entry2.get() with open("userpassdata","r") as f: for line in f: lst = line lst = lst.replace("'","") lst = lst.replace(" ","") lst= lst.strip("[] \n") ls = lst.split(",") userdata = [] print(ls) if ls != ['!!confidential!!']: usern = decrypt(ls[0],ls[2]) userp = decrypt(ls[1],ls[2]) userdata = [usern, userp, ls[2]] if userdata[0] == user and userdata[1] == password and int(ls[2]) <= 100: start.place_forget() with open("usersprivate","r") as f: for line2 in f: if user in line2: uun = line2.split(",") uun.pop(-1) un = "" un = un.join(uun) break signed.place(relwidth = 500, relheight = 500) sighendscreen(un,user) return elif userdata[0] == user and userdata[1] == password and int(ls[2]) > 100: start.place_forget() with open("usersprivate","r") as f: for line2 in f: if user in line2: uun = line2.split(",") uun.pop(-1) un = "" un = un.join(uun) break signeduser.place(relwidth = 500, relheight = 500) sighendscreen2(un,user) return else: print("fail2") l5_1.place(anchor = "center",x = 250, y = 100)
def __decodedString(self, string): while True: password = input("Introduzca Clave de cifrado: ") decoded = cryptocode.decrypt(string, password) if decoded != False: self.password = password return decoded else: continue
def get_pass_from_base(txt): try: with open('datainfo.txt', 'r+') as f: content = f.readlines() print(content) p_1 = content[0] e_1 = content[1] r_password = cryptocode.decrypt(p_1, decrypt_key) r_email = cryptocode.decrypt(e_1, decrypt_key) print(r_password) if txt == 'raw_email': return r_email elif txt == "raw_password": return r_password else: pass except IndexError: pass
def set_ciphers(self): """ Picks random ciphertext from clear_text list and enciphers it with a random Caesar cipher. The generated ciphers are added to the associated workout datastore entry. :arg: workout_id: type(str) :return: cipher_list: type(list) """ key = ds_client.key('cybergym-workout', self.workout_id) workout = ds_client.get(key) result = [] ciphertext = [ 'cHrJdEdTf0hyNgw5zF1M5Z0/ITEMcBZBhBQHzNBGBv7o3LvkYb+TjwOjO67FrkXtIIEdLXsqmXXRPagkIMrzEg==*svFn1+TLeh98KnWhiMMBDg==*FOt35Q8pYVsaTzhdpPjlFw==*aCJPMiRxEjwNQhrSlqysiw==', 'qxHOa703kkPl/7lAcrkg7vO4ls2CeitgI3i6KdqrgvT2*Qci2czk/yYe/CAHdRyysRw==*UGU5zGXgsjpE1YmFEK/gOA==*QIHWApOhCNhdPii7zmwiQQ==', 'gsER0I6djkzkcMWy4dXm6gMqQIEAWEaY6w5QZcs8JA==*VRgmiO52cs2rhXPyl/JQUA==*UYS5O0NR0PQ+oVHPgiuYlQ==*dcXm+LhIOogUMk6Ai3llUA==', 'YwSEGVOsr6ETK9RkiDbW/T63YgwMlflejuAHb2D27uWUxxNM+8GyKQNYpvHPF61oAqF2MJx6vm23DlbQsKYDNt3rSozKme2M*Y5H9N0qglUGkPQogEXoWag==*rZYHlsmZHhrL3t/QXQappw==*HEwB7CCansYAnFfkyZp+Iw==', 'T1qs1d3QeEhOtw0HnYa6Km/4u22C4HxnJo1U3PmmbK3P7RjX1sKQSK/tE21vAmPjeyZHsXkivOLaxnDepsBY*LxgEbXraHwGLcqqWTQ8nJw==*Wm5yQsNBFZexuKh0qNHXgQ==*nB3mcG1/YP3650woabP/rA==', 'vi0vzFK0kdQxmQmQfNWJ8Z0EhalOWZIl*PLnhb4UJNEjsB77R4jfdpg==*iUAOTNTMla2BUC+Ptlwrxg==*XvNyPHdJbvpsEgpciCTO2A==', 'pdLsU9mt8b8jAcks0PsVMXLLJ7TI*s3bL+SYzb8a7LO5A28vPpA==*+ngLia29sega2aCNcZVMNg==*5K72D0Sd/LjzFpTWNlT8WQ==', 'EkqGEBmXlfyqIpRfs/H4arDRddhbyzSci9qiDL/rdxZly9Hf9dpvZT+E81zN/z/I6r+Igw==*n3JelIgumPF5/6U8QWSP5w==*ljH0w3Qew+A0MDHawnj7pg==*dJ0mPniIqx7H/vCq9AIvnQ==', '1I0XgyuMKjs1kPk1DQVii5j5jMqiFmfBnPsbGQTmA3Zw0WRGrgRzVk2uLuj3PbOao/O+DAR5j1a3BxWkoZuj/TiSr+/DB++R7A4=*5nK6m5wjd//mpcAme38eJA==*fE+KsmGL0kJr59cewvhw3g==*M4MO0kfYGYRftk9ly0SV5w==', 'cQrxJ/jtxbAU6LRaMHFhcRitOAKdYk9I8lBtcJJMjdz1BbccFOnHdNBo8cnV4yiwFg4p1g==*t3wlFteyvKkMMu/sUxwFrA==*jpXTlFx/uROFEU4LRrKCcg==*xVdbwGW77gfK+RcVdAh/mw==', '5vSfmSSYgrAAVnx1eN/TAk2Gwr7J7bc/5Z2iz2Gdt5cYW8kayzPffBlwuk4zAu0MIQ==*runx4j1oS+EDmqQzTpffIQ==*PsieshpViBqbShXaWS8JoQ==*fNVQW0lGi295x2iXPTYu8g==', 'yP4Wx01uE43qhDno6t7T3dhrAMttrQohjhD7qX1j2SGRcw==*AraEUK9HFWO9t1XnO5LPOA==*lVRy99cNGPQFulT0eKiOMA==*D5mbvsxKpugrICDLCO1iCw==', 'xuesxMYtGNWZauNNcaT/WaethacFcQKse/VZyNNbmgnQrjApUxtez6cxYoCZZD/TdaSCUZNF+SKP90GppKnhmPUFTq+euW1YRR5k*WlwVeUOakP8HqXjX0nFEQQ==*+ofoLoHhqFBda7MbIispBg==*Key7If3+PxitkHopiRg/Jw==', 'n0KJy+51I7tLri7d2/d8IYE8fLXdshDpW0sT0kZT3AZsUfPRg5s=*M4xt8Lgc6PlKESFNt+0UyA==*tcTzgpB3K85Wv79Nvwaa/g==*EJyW/6GQ9l8tVRamYxJl/g==', '8ky3P4KzaiapBKSegsOna7RFIIy0cRy/6ndP*Ib9X6xNjJOvD1dWKLBh71w==*30Tp8YFOpENL9TcLTSLKtA==*f19cK1e96JXNs5tnlg/VzQ==', 'iGN3lzZ9siVuP6BiB/oyMUaTKwc1Xro=*7QBuorkbgqg8AG7VJKK48g==*xwr5VPY1MoqQDlk1KCxFuA==*5p3v7La7vgQZPI6sOZj6IQ==', 'l2PhriCMAaLjzL6lw09krXdChsfRqGVs27N76PwLYsxDAy3+7ppNkJA+8MT4ATZ621UHQnSQC5tFwtSDtyY=*YlOQAhSxb349lOSqmbfqLA==*2UxT2+s+S9cxm5LD8r70Dw==*24TuHNvrMvvFYNjwGnFWdg==', '9SXrAaCYO5RVs1ZysuPKxg84Cuxvnv5p4lFVRDesi54tTdi8tqJ6ioSaig==*ig3XNhkzjep/z7LjKS9Bsg==*G0xLttPhJs5yianF+GeR5w==*zOBj+Xil7SnvdKiMWUYdTg==', '3cCIJcW3NtIDibjxejvNLWr2PomtFOr3ZdEc3m/+QScyfKQw5ISGT5QR6CD6VuBnwJrfgnFo*d1JrIY35CEXqKgxhICZ8UA==*YpWtqeEf9/GaTxpdvIb05g==*RnbmvSERZZvtBNhUIwnTvA==' ] decrypt_key = workout['assessment']['key'] for pos in range(len(ciphertext)): key = random.randrange(1, 25) clear_text = cryptocode.decrypt(ciphertext[pos], decrypt_key) cipher_string = CaesarCipher(clear_text, offset=key).encoded cipher = { 'key': key, 'cipher': cipher_string, } result.append(cipher) # Selects 3 unique ciphers from list cipher_list = random.sample(result, k=3) workout['container_info']['cipher_one'] = cipher_list[0] workout['container_info']['cipher_two'] = cipher_list[1] workout['container_info']['cipher_three'] = cipher_list[2] ds_client.put(workout) return cipher_list
def snake_flag(workout_id): key = ds_client.key('cybergym-workout', workout_id) workout = ds_client.get(key) if request.method == 'POST': score = (request.json['score']) decrypt_key = workout['assessment']['key'] encrypted_flag = 'KJnLMnsUnLCd/ND3eeJwWPINTzvXTKiiYoNkmjCwbng=*xzz+f0pzhaBX41kaZH3GQg==*+JgHfNlMoOsd7GlTXGqW' \ 'Fw==*djY9r0Kb0hQb0B7cNZOr4A==' flag = cryptocode.decrypt(encrypted_flag, decrypt_key) flag_data = {'flag': str(flag)} return jsonify(flag_data)
def with_variables(): #password for our string password = "******" #text to encode encrypted_text = "H4ZNKr0F*6kiRydXO550rftyRQQCXhg==*jdR59rxV41HS2pycnHFq7Q==*49YFs7DL8Z1FA2Q+0wOA/A==" #encoding text encoded = cryptocode.decrypt(encrypted_text, password) #printing print(encoded)
def home(workout_id): key = ds_client.key('cybergym-workout', workout_id) workout = ds_client.get(key) if not session.get('logged_in'): return render_template('index.html', workout_id=workout_id) else: decrypt_key = workout['assessment']['key'] encrypted_flag = 'w7w1HZQSOlQk7cxRjqICoIXkFbUsjnr9CHJkvZ51Iw==*9o+WrK5lFOZG70IARQ5HGA==*7bLeQoMR/IhXQjlvey' \ '71KQ==*D+iRjmWUsHXkKTC+G6cF4g==' wireshark_flag = cryptocode.decrypt(encrypted_flag, decrypt_key) return render_template('flag.html', wireshark_flag=wireshark_flag, workout_id=workout_id)
def twofactorhome(workout_id): page_template = 'welcome.html' key = ds_client.key('cybergym-workout', workout_id) workout = ds_client.get(key) if workout['type'] == '2fa': decrypt_key = workout['assessment']['key'] encrypted_flag = 'IpmnWmd6aeyrsrCmcaljIVU19XOmFOKtr9B3OXChIbbZXbQ=*lbG7TJXiAIIS8cQtG9Nufw==*wrSgLeSlwVSCzwm' \ 'rlpRlRQ==*c6Oj6lsCnrwLVIXgp0c6vg==' flag = str(cryptocode.decrypt(encrypted_flag, decrypt_key)) return render_template(page_template, flag=flag, workout_id=workout_id) else: return redirect(404)
def DPLogin(request): if request.method == 'POST': data = json.loads(request.body) if data['select'] == 'Patient': query = PatientRegister.objects.all().filter(email=data['email']).first() if query and cryptocode.decrypt(query.password,encrypt_key ) == data['password']: return HttpResponse('Patient Login successful ',status=200) else: return HttpResponse('Invalid Credentials',status=404) elif data['select'] == 'Doctor': query = DoctorRegister.objects.all().filter(email=data['email']).first() if query and cryptocode.decrypt(query.password,encrypt_key ) == data['password']: return HttpResponse('Patient Login successful ',status=200) else: return HttpResponse('Invalid Credentials',status=404) else: return HttpResponse('bad request',status=404) else: return HttpResponse('bad request',status=404)
def asking_for_pass_and_text(): #asking for password for our string print("Please enter the password") password = input() #asking for text to encode print("Please enter the encrypted text") encrypted_text = input() #encoding text encoded = cryptocode.decrypt(encrypted_text, password) #printing print(encoded)
def client(): host = "127.0.0.1" port = 5001 c = socket.socket() c.connect((host, port)) message = input("Input:: ") while message.lower().strip() != 'end': message = cryptocode.encrypt(message, "mysecret") c.send(message.encode()) data = c.recv(1024).decode() data = cryptocode.decrypt(message, "mysecret") print('Server message: ' + data) message = input(" >") c.close()
def get_password(conn, user_id, app_name, password): '''Gets the password and copies to cpliboard''' sql = "SELECT password FROM password WHERE user_id= '" + str( user_id) + "' AND app_name= '" + app_name + "' " cursor = conn.cursor() cursor.execute(sql) res = cursor.fetchall() print(color['WARNING'] + 'No password found by app name' + color['ENDC'] if res == [] else color['WARNING'] + 'Copied to Clip board' + color['ENDC'], end=' ') password = cryptocode.decrypt(res[0][0], password) print(f'{app_name} : {password}') pyperclip.copy(password)
def check_flag(workout_id): page_template = 'arena_snake.html' if request.method == 'POST': key = ds_client.key('cybergym-workout', workout_id) workout = ds_client.get(key) workout_token = workout['assessment']['questions'][0]['key'] if request.form.get('check_button'): decrypt_key = workout['assessment']['key'] encrypted_flag = 'KJnLMnsUnLCd/ND3eeJwWPINTzvXTKiiYoNkmjCwbng=*xzz+f0pzhaBX41kaZH3GQg==*+JgHfNlMoOsd7GlTXGqW' \ 'Fw==*djY9r0Kb0hQb0B7cNZOr4A==' classified_flag = cryptocode.decrypt(encrypted_flag, decrypt_key) if classified_flag == request.form['classified_flag']: publish_status(workout_id, workout_token) completion = True return render_template(page_template, workout_id=workout_id, completion=completion) else: return render_template(page_template, workout_id=workout_id)
def server(): host = "127.0.0.1" port = 5001 s = socket.socket() s.bind((host, port)) s.listen(2) conn, address = s.accept() print("New Connection From:" + str(address)) while True: data = conn.recv(1024).decode() if not data: break data = str(data) data = cryptocode.decrypt(data, "mysecret") print("User: "******"mysecret") conn.send(data.encode()) conn.close()
def check_flag(workout_id): if request.method == 'POST': key = ds_client.key('cybergym-workout', workout_id) page_template = 'sql_index.html' workout = ds_client.get(key) workout_token = workout['assessment']['questions'][0]['key'] if request.form.get('check_button'): decrypt_key = workout['assessment']['key'] encr_flag = "z3iMRhodBpfpOPQalsurIEQmbjpv52PYL0HDnqxCVyu+aQCVTRPWBNv6QI8U*fQKWPyfP5gtUExz5MnLuWg==" \ "*5j/Up6s28F82Am+O7HTfHQ==*M2pIUrpUwaAXlc4ohBKpxQ==" classified_flag = cryptocode.decrypt(encr_flag, decrypt_key) if classified_flag == request.form['classified_flag']: publish_status(workout_id, workout_token) completion = True return render_template(page_template, workout_id=workout_id, completion=completion) else: return render_template(page_template, workout_id=workout_id)
def check_flag(workout_id): if request.method == 'POST': key = ds_client.key('cybergym-workout', workout_id) page_template = 'inspect.html' workout = ds_client.get(key) workout_token = workout['assessment']['questions'][0]['key'] if request.form.get('check_button'): decrypt_key = workout['assessment']['key'] encrypted_flag = 'gecJuFQuv1FhQAfLDvn9f6j6xu/GACm00wqyoWVKUJQ=*gXSP1UFZELV59Qz6yP0Y+w==*' \ 'y6cg3ujMtm7eSklW2SX3JQ==*C4GDYpzjfozIsTQWVuUc4A==' classified_flag = cryptocode.decrypt(encrypted_flag, decrypt_key) if classified_flag == request.form['classified_flag']: publish_status(workout_id, workout_token) completion = True return render_template(page_template, workout_id=workout_id, completion=completion) else: return render_template(page_template, workout_id=workout_id)
def login_sql(workout_id): if request.method == 'POST': key = ds_client.key('cybergym-workout', workout_id) workout = ds_client.get(key) # Get login form data and attempt login uname, pword = (request.json['username'], request.json['password']) g.db = connect_db() cur = g.db.execute( "SELECT * FROM employees WHERE username = '******' AND password = '******'" % (uname, hash_pass(pword))) # Credentials exist, decrypt and return flag if cur.fetchone(): decrypt_key = workout['assessment']['key'] encr_flag = "z3iMRhodBpfpOPQalsurIEQmbjpv52PYL0HDnqxCVyu+aQCVTRPWBNv6QI8U*fQKWPyfP5gtUExz5MnLuWg==" \ "*5j/Up6s28F82Am+O7HTfHQ==*M2pIUrpUwaAXlc4ohBKpxQ==" flag = cryptocode.decrypt(encr_flag, decrypt_key) result = {'status': 'success', 'flag': flag} else: result = {'status': 'fail'} g.db.close() return jsonify(result)
def login(workout_id): page_template = 'inspect.html' key = ds_client.key('cybergym-workout', workout_id) workout = ds_client.get(key) if workout['type'] == 'inspect': if request.method == 'POST': if request.form['password'] == 'TrojanSpirit!2021' and request.form[ 'username'] == 'Maximus': decrypt_key = workout['assessment']['key'] classified_flag = 'gecJuFQuv1FhQAfLDvn9f6j6xu/GACm00wqyoWVKUJQ=*gXSP1UFZELV59Qz6yP0Y+w==*' \ 'y6cg3ujMtm7eSklW2SX3JQ==*C4GDYpzjfozIsTQWVuUc4A==' plaintext_flag = cryptocode.decrypt(classified_flag, decrypt_key) return render_template(page_template, workout_id=workout_id, classified_flag=plaintext_flag) else: return redirect( url_for('inspect_bp.xsfiedSTRflag ', workout_id=workout_id)) else: return redirect(404)
def process(): ''' Client extract information from website. It will validate the input. It checks the password by checking with the password manager (using hashes). The password manager will return encrypted private key for RSA signing. It will perform homomorphic encryption with the public key from "decrypt_server", sign the ballot with the RSA private key and sent it to the server. The whole part would be encrypted and the server that performs the addition of the ballot to the tally cannot see the voter's candidate election. ''' if (request.method == 'POST'): data = request.json if data: #values extracted from the page id_value = data['id_num'] password = data['password'] input_val = int(data['input']) ''' Data validators ''' #checks if no selection is made if input_val == -1: return warnings("No selection") #checks if no id number was entered if id_value == "": return warnings("Enter a valid Id") #checks if a password was provided if password == "": return warnings("No password provided.") ''' Built the ballot and encrypt it ''' #build ballot vote_list = [ 0, 0, 0, 0 ] # representation of a ballot. Each index represent a cadidate. We enforce one vote per ballot by using droplist in the frontend vote_list[ input_val] = 1 # set to 1 the index number of the choosen candidate public_key_rec = get_public_key_he( ) #gets public key to encrypt the ballot for Homomorphic encryption ballot = encrypt( public_key_rec, vote_list ) # perform H.E encryption on the values from the list. ''' Sign the ballot with the voter private key - get salt from the password_manager - hash with the salt (5001 rounds) - use this hash to authe. and get encryoted priv. key - decrypt priv key with the hash + salt but with 5000 rounds - use the encrypted values of the ballloot to generate a hash and sign it with priv key ''' temp_salt = requests.post( 'http://password_manager:6000/salt', json=json.dumps([id_value]) ) #gets "salt" from the password manager database to generate the hash value. salt = json.loads(temp_salt.text) if salt == 1: # if "salt" returns 1, then there is no associeted account with the voter return warnings("Voter no registered") #generates both hashes to authe. and decrypt the password_manager encrypted key password_decrypt, password_aunthticate = generate_hashes( password, salt) # obtain the private key. sends the hashed password with salt and the id number auth_kit = [ id_value, password_aunthticate.hex() ] # data need to auuthenticate and download encrypted key temp_private_key = requests.post( 'http://password_manager:6000/download', json=json.dumps(auth_kit) ) #aunthenticate and download encrypted private key private_key = json.loads( temp_private_key.text ) # gets the encrypted privsate key or 1 if it's not successful if private_key == 1: # if the password_auth doesn't match inside password_manager, stop. It won't try to decrypt return warnings("Authentication failed") decrypt_key = cryptocode.decrypt(private_key, password_decrypt.hex( )) #encrypts the private key using "password_hash" packet_values = ballot[ 'values'] # extract raw encrypter ciphertext to sign up the code message = hash_integrity( packet_values ) # created hash with the encrypted values of the ballot. encoded = sign_comm( message, decrypt_key ) #sign the message to perform integrity verificatin ''' "Paquete" contains the encrypted ballot, the voter's id and the signature to check integrity This is the step where it's sent to the server ''' paquete = [ballot, data['id_num'], encoded] #forms list with the parts to be sent. temp = requests.post( 'http://server', json=json.dumps(paquete) ) #send data to the server to be added to the tally. Data is already encrypted encrypted. ''' Get an answer from the server if it was successful or not ''' results = json.loads( temp.text ) #gets sucess or fail, depents on the results of the vote counting confirmation = json.dumps(results) app.logger.info(confirmation) return confirmation
def decode_url_string(url_str): percent_dec = parse.unquote(url_str) cryptcode_dec = cryptocode.decrypt(percent_dec, os.environ.get("SECRET_KEY")) return cryptcode_dec
def retrievePrivate(self, password): file = open("wallet.dat", 'r') wallet = json.loads(file.read()) file.close() return cryptocode.decrypt(wallet["privateHex"], password)
import os import sys from cryptocode import encrypt, decrypt data = sys.argv[1] password = sys.argv[2] cyphertext = encrypt(data, password) print(cyphertext) myDecryptedMessage = decrypt(cyphertext, password) print(myDecryptedMessage)