Exemplo n.º 1
0
def verify_dh_key_exchange():
    client_uuid = request.args.get("a")
    client_password = request.args.get("b")

    print(client_password)

    temp_state = copy.deepcopy(STORE["clients"][client_uuid])

    if client_uuid != temp_state["id"]:
        return jsonify({"status": "error"})

    decrypt(temp_state, client_password)

    client_password = temp_state["receiving_msg"]

    client_password_hash = hashlib.new("SHA256")
    client_password_hash.update(bytes(client_password, "utf-8"))
    client_password_hash = client_password_hash.hexdigest()

    if client_password_hash != temp_state["password"]:
        return jsonify({"status": "error"})

    print(client_password)
    print(client_password_hash)
    print(temp_state["password"])

    STORE["clients"][client_uuid] = temp_state

    return jsonify({"status": "ok"})
Exemplo n.º 2
0
Arquivo: user.py Projeto: t2d/pyanotel
    def handle_paging(self, payload):
        """ Handle paging packet """
        # find amount of paging signals
        amount = len(payload) / 2
        pseudos = payload[:amount]
        call = False
        used_name = None

        # check for pseudonym and paging names
        if self.user.pseudonym in pseudos:
            print "Found my pseudonym!"
            index = pseudos.index(self.user.pseudonym)
            # L did broadcast, send location update
            used_name = self.user.pseudonym
        elif self.user.paging_names is not None:
            for name in self.user.paging_names:
                if name in pseudos:
                    print "Found a paging name: %s" % name
                    index = pseudos.index(name)
                    used_name = name
                    break
            if used_name is None:
                # packet not for me
                return
            elif used_name == self.user.pseudonym:
                # was broadcast -> full location update
                self.user.update_providers()
            else:
                # update paging names
                self.user.paging_names = create_paging_names(self.user.seed, used_name, amount=100)
        else:
            # packet not for me
            return

        # try to decrypt the paging packet
        try:
            cid, caller = decrypt(payload[amount + index], self.user.secret)
        except ValueError:
            print "Was no well-formed ciphertext"
        else:
            # check if cid is msg
            if cid.startswith("M:"):  # suboptimal, will eat calls
                msg = get_msg(cid)
                print "MSG: %s from %s" % (msg, caller)
            # check if we have seen this packet before
            elif cid not in self.used_cids:
                # really incoming call
                self.used_cids.append(cid)
                # Ask if user wants to take call
                self.user.io.transport.write("Do you want to take the call of %s? (y/n)\n" % caller)
                self.user.incoming_call = (cid, caller)
    '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)
Exemplo n.º 4
0
# -*- coding: utf-8 -*-
import select, socket
from helpers import decrypt

# SOCKET
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(("127.0.0.1", 5005))
sock.listen(99)

while True:
    conn, address = sock.accept()
    buf = conn.recv(4096)
    msg = decrypt(buf)[
        1:
        -1]  # WORKAROUND: DURANTE O DECRYPT E ADICIONADO ASPAS NO INICIO E FIM
    print msg
    conn.send(msg)
Exemplo n.º 5
0
 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)
Exemplo n.º 6
0
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!!")
Exemplo n.º 7
0
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
Exemplo n.º 8
0
    s_w1, h_w1 = sign_msg(w1, priv_key, E)  # my function to sign messages
    pl_txt = ("s" + str(s_w1) + "h" + str(h_w1)).encode("utf-8")

    # Encyption
    cip = AES.new(K.digest(), AES.MODE_CTR)
    Y1 = cip.nonce + cip.encrypt(pl_txt)
    ctext = int.from_bytes(Y1, byteorder="big")

    ###Send encrypted-signed keys and retrive server's signed keys
    mes = {'ID': stuID, 'FINAL MESSAGE': ctext}
    response = requests.put('{}/{}'.format(API_URL, "STSStep4&5"), json=mes)
    if ((response.ok) == False): raise Exception(response.json())
    ctext = response.json()

    # Decrypt
    dtext = decrypt(ctext, AES.MODE_CTR, K)  # decrypt function i implemented.

    # verify
    w2 = str(SKEY.x) + str(SKEY.y) + str(ekey.x) + str(
        ekey.y)  # msg that server side signs
    s_w2 = int(dtext[1:dtext.index("h")])
    h_w2 = int(dtext[dtext.index("h") + 1:])
    V = s_w2 * P - h_w2 * QSer_long
    v = V.x % n
    h_ = SHA3_256.new(
        w2.encode("utf-8") +
        v.to_bytes((v.bit_length() + 7) // 8, byteorder='big'))
    h_ = int.from_bytes(h_.digest(), byteorder='big') % n
    #print("h_ = ",h_)
    #print("h_w2 = ", h_w2)
    print("Result of the signature verification in 2.5: ",