def dh_key_exchange(): temp_state = new_actor_state() temp_state["dh_exchange_nums"]["s"] = generate_prime_number(8) temp_state["dh_exchange_nums"]["p"] = int(request.args.get("a")) temp_state["dh_exchange_nums"]["g"] = int(request.args.get("b")) temp_state["dh_exchange_nums"]["A"] = int(request.args.get("c")) temp_state["dh_exchange_nums"]["B"] = \ temp_state["dh_exchange_nums"]["g"] ** \ temp_state["dh_exchange_nums"]["s"] % \ temp_state["dh_exchange_nums"]["p"] temp_state["dh_exchange_nums"]["key"] = \ temp_state["dh_exchange_nums"]["A"] ** \ temp_state["dh_exchange_nums"]["s"] % \ temp_state["dh_exchange_nums"]["p"] temp_state["secret_key"] = str(temp_state["dh_exchange_nums"]["key"]) client_uuid = str(uuid.uuid4()) client_password = str(uuid.uuid4()) client_password_hash = hashlib.new("SHA256") client_password_hash.update(bytes(client_password, "utf-8")) client_password_hash = client_password_hash.hexdigest() temp_state["id"] = client_uuid temp_state["password"] = client_password_hash encrypt(temp_state, json.dumps({ "id": client_uuid, "password": client_password })) STORE["clients"][client_uuid] = temp_state print("B") print(str(temp_state["dh_exchange_nums"]["B"])) print("sec_key") print(STORE["clients"][client_uuid]["secret_key"]) print("id") print(client_uuid) print("password hash") print(STORE["clients"][client_uuid]["password"]) print("password") print(client_password) print("sending msg") print(STORE["clients"][client_uuid]["sending_msg"]) return jsonify({ "B": str(STORE["clients"][client_uuid]["dh_exchange_nums"]["B"]), "payload": STORE["clients"][client_uuid]["sending_msg"] })
def submit(): text = request.form['originaltext'] rotate = int(request.form['rotate']) encrypt_text = encrypt(text, rotate) return_text = '' for char in encrypt_text: if (char == '\n'): return_text = f'{return_text}<br>' else: return_text = f'{return_text}{char}' strng = """ <html> <head> <style> body { background-color: #eee; padding: 20px; margin: 0 auto; width: 540px; font: 16px sans-serif; border-radius: 10px; } textarea { margin: 10px 0; width: 540px; height: 120px; } </style> </head> <body> """ return_text = f'{strng}\n<h1>The encrypted text is :</h1>\n<br><p>{return_text}</p></body></html>' return return_text
def send_msg(self, callee, caller, msg): try: assert len(msg) <= constants.word_len pseudonym = self.pseudonyms[callee] except KeyError: print "Unknown recipient %s" % callee else: blob = encrypt([msg, caller], self.secrets[callee]) self.L.init_call(pseudonym, blob)
def check_secret_token(email, token): valid_till, enc_email_ts = token.split('@') tampered = helpers.encrypt(email + valid_till) != enc_email_ts def expired(): today = datetime.date.today() valid_date = datetime.date(*[int(t) for t in valid_till.split('-')]) return today > valid_date return not(tampered or expired())
def encrypt_password(self, key, password): if password != self.password: if re.match(r'^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,15}$', password): return helpers.encrypt(password) else: raise ValueError( "Password must be 6 to 15 characters long, contain at least one: " "uppercase letter, lowercase letter, a digit") else: return password
def check_secret_token(email, token): valid_till, enc_email_ts = token.split('@') tampered = helpers.encrypt(email + valid_till) != enc_email_ts def expired(): today = datetime.date.today() valid_date = datetime.date(*[int(t) for t in valid_till.split('-')]) return today > valid_date return not (tampered or expired())
def aespt(): if request.method == "GET": if not request.args.get("plaintext"): return jsonify({"message": "128bit AES"}) plaintext = request.args.get("plaintext") try: ciphertext = helpers.encrypt(plaintext) return jsonify({"ciphertext": ciphertext}) except: return jsonify({'error': "Invalid Input"})
def main(): if user_input_is_valid(argv) == False: print("usage: python3 caesar.py n") exit(1) message = input("Type a message:\n") key = int(argv[1]) scrambled = encrypt(message, key) print("ciphertext: " + scrambled)
def init_call(self, callee, caller, pseudonym, connection): # check validity of caller if self.pseudonyms[caller] == pseudonym: cid = pick_random() try: assert len(callee) == constants.word_len assert len(caller) == constants.word_len pseudonym = self.pseudonyms[callee] except KeyError: print "Call for unknown user" except AssertionError: print "IDs have wrong length." else: self.calls[cid] = [callee, caller, connection] blob = encrypt([cid, caller], self.secrets[callee]) self.L.init_call(pseudonym, blob) self.N.init_call(cid)
def get_secret_token(email, validity=7): valid_till = (datetime.date.today() + datetime.timedelta(validity)).isoformat() return '@'.join([valid_till, helpers.encrypt(email + valid_till)])
def test_encryption(self): test_string = helpers.pick_random() ciphertext = helpers.encrypt(test_string, constants.user1_secret) plaintext = helpers.decrypt(ciphertext, constants.user1_secret) self.assertEqual(test_string, plaintext)
def main(): """ Part-1: Payment Request Generation """ print("-------------------------------------------------------") print("---PAYMENT REQUEST GENERATION---") cust_privkey, cust_pubkey = rsakeys() bank_privkey, bank_pubkey = rsakeys() print("Customer's private key-", cust_privkey) print("Customer's public key-", cust_pubkey) print("Bank's private key-", bank_privkey) print("Bank's public key-", bank_pubkey) payment_info = 'Some payment information' order_info = 'Some order information' PIMD = get_hash(payment_info) OIMD = get_hash(order_info) POMD = get_hash(PIMD + OIMD) dual_sign = sign(cust_privkey, POMD) key_s = aeskey() encrypted_pi, iv_pi = aesencrypt(payment_info, key_s) encrypted_oimd, iv_oimd = aesencrypt(OIMD, key_s) encrypted_ds, iv_ds = aesencrypt(dual_sign, key_s) digital_envelope = encrypt(bank_pubkey, key_s) """ Part 2: Purchase Request Validation from Merchant side """ merchant_oimd = get_hash(order_info) merchant_pomd = get_hash(PIMD + merchant_oimd) check_sign_merchant = verify(cust_pubkey, merchant_pomd, dual_sign) if check_sign_merchant: print("-------------------------------------------------------") print("[INFO] Merchant Signatures match") print("\tPurchase request validated by merchant") print("\t---PURCHASE REQUEST VALIDATED---") print("-------------------------------------------------------") else: print("-------------------------------------------------------") print("[INFO] Signatures do not match") print("\tPurchace request rejected- Signatures do not match!!") return """ Part 3: Payment authorization """ bank_key_s = decrypt(bank_privkey, digital_envelope) bank_pi = aesdecrypt(encrypted_pi, bank_key_s, iv_pi).decode() bank_oimd = aesdecrypt(encrypted_oimd, bank_key_s, iv_oimd).decode() bank_ds = aesdecrypt(encrypted_ds, bank_key_s, iv_ds) bank_pimd = get_hash(bank_pi) bank_pomd = get_hash(bank_pimd + bank_oimd) check_sign_bank = verify(cust_pubkey, bank_pomd, dual_sign) if check_sign_bank: print("[INFO] Bank Signatures match") print("\tPayment authorized by the bank") print("\t---PAYMENT AUTHORIZATION SUCCESSFUL---") print("-------------------------------------------------------") print("\t---PAYMENT CAPTURE SUCCESSFUL---") print("-------------------------------------------------------") else: print("[INFO] Signatures do not match") print("\tPayment authorization failed- Signatures do not match!!")
def main(): phrase = input("What phrase would you like encrypted?") code_word = input("What is your encryption word?") coded_phrase = encrypt(phrase, code_word) print(coded_phrase)
def dh_key_exchange_with(): temp_state = new_actor_state() temp_state["dh_exchange_nums"]["s"] = generate_prime_number(8) temp_state["dh_exchange_nums"]["p"] = generate_prime_number(16) temp_state["dh_exchange_nums"]["g"] = generate_prime_number(8) temp_state["dh_exchange_nums"]["A"] = \ temp_state["dh_exchange_nums"]["g"] ** \ temp_state["dh_exchange_nums"]["s"] % \ temp_state["dh_exchange_nums"]["p"] response = requests.post( f'http://localhost:5000/dh_key_exchange?' + \ f'a={str(temp_state["dh_exchange_nums"]["p"])}&' + \ f'b={str(temp_state["dh_exchange_nums"]["g"])}&' + \ f'c={str(temp_state["dh_exchange_nums"]["A"])}' ) if response.status_code != 200: print("HTTP ERROR CODE: " + str(response.status_code)) return False response = json.loads(response.text) temp_state["dh_exchange_nums"]["B"] = int(response["B"]) temp_state["dh_exchange_nums"]["key"] = \ temp_state["dh_exchange_nums"]["B"] ** \ temp_state["dh_exchange_nums"]["s"] % \ temp_state["dh_exchange_nums"]["p"] temp_state["secret_key"] = str(temp_state["dh_exchange_nums"]["key"]) decrypt(temp_state, response["payload"]) payload = json.loads(temp_state["receiving_msg"]) temp_state["id"] = payload["id"] temp_state["password"] = payload["password"] print(response) print(temp_state["secret_key"]) print(temp_state["receiving_msg"]) print(temp_state["password"]) print(temp_state["id"]) new_temp_state = copy.deepcopy(temp_state) encrypt(new_temp_state, new_temp_state["password"]) response = requests.post( f'http://localhost:5000/verify_dh_key_exchange?' + \ f'a={new_temp_state["id"]}&' + \ f'b={new_temp_state["sending_msg"]}' ) if response.status_code != 200: print("HTTP ERROR CODE: " + str(response.status_code)) return False response = json.loads(response.text) print(response) temp_state = copy.deepcopy(new_temp_state) return True
'n': '14', 'o': '15', 'p': '16', 'q': '17', 'r': '18', 's': '19', 't': '20', 'u': '21', 'v': '22', 'w': '23', 'x': '24', 'y': '25', 'a': '26', '@': '27', '$': '28', '#': '29', '%': '30', '&': '31', '*': '32', 'z': '33', '(': '34' } plain_text = "jack mohammad amr judy" print("Plain Text: " + plain_text) cipher = encrypt(N, e, plain_text, key) print("Cipher Text: " + cipher) decrypted_text = decrypt(N, e, cipher, key) print("Decrypted Text: " + decrypted_text)
# -*- coding: utf-8 -*- import socket, select, sys from helpers import encrypt msg = sys.argv[1] # SOCKET sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect(("127.0.0.1", 5005)) sock.sendall(encrypt(msg)) data = sock.recv(1024) if msg == data: print "O servidor retornou com a mensagem correta. =D : ", msg sys.exit() print "O servidor não conseguiu desencriptar a mensagem. =( : ", msg