Exemple #1
0
def validate(share, share_conn):

    #quit if the user is attempting to authorize more than 5 seconds after submitting their third share
    if time.time() - int(share["timestamp"]) > 5:
        print("No auth for you, timeout!")
        return

    #quit if an innapropriate number of shares has been sumbitted, log the number stored currently
    if not share["num_shares"] == settings.THRESH:
        print(share["id"] + " has submitted " + str(share["num_shares"]) +
              " shares!")
        return

    #create object holding the shares within tuples (nessecary for shamir library)
    s = []
    for i in range(settings.THRESH):
        s.append((int(share["x" + str(i + 1)]), int(share["y" + str(i + 1)])))

    #recover the secret from the shares list
    secret = shamir.recover_secret(s)

    #open connection to secrets database and set up cursor
    conn = sqlite3.connect(settings.DBdir + "secrets.db")
    conn.row_factory = sqlite3.Row
    c = conn.cursor()

    #select user's secret by ID
    c.execute("SELECT * FROM secrets WHERE id = ?", [share["id"]])
    res = c.fetchone()

    #if the secret recovered from the shares db matches the stored secret the user is authenticated
    if res["secret"] == str(secret):

        #authorize the user (this is where the "door open", or "ssh successful" code would be in the real world)
        print(res["name"] + " is Authorized!")

        #Let user be authorised for 10 seconds
        time.sleep(10)

        #delete shares information so that users cannot auth twice for free
        share_conn.cursor().execute("DELETE FROM shares WHERE id = ?",
                                    [share['id']])
        share_conn.commit()

    else:

        #deny user authentication
        print("No auth for you!")

    #close db connections
    conn.close()
    share_conn.close()
    return
Exemple #2
0
def generate_secret_from_msg(msg, req, total):
    """
	:param msg: the msg to hide
	:param req: how many points need to recover the msg
	:param total: how many point to create
	:return: points to send to servers
	"""
    secret, points = __make_msg_secret_shares(msg, req, total)
    if len(msg) > MAX_MSG_LEN:
        errmsg = "msg can't be recovered, the msg is too long.\n" \
           "max len is " + MAX_MSG_LEN + " chars, your msg len is " + str(len(msg)) + " chars"
        raise ValueError(errmsg)
    if msg != int_to_str(shamir.recover_secret(points, PRIME)):
        errmsg = "msg can't be recovered, for unknown reason, please contact us"
        raise ValueError(errmsg)
    return points
Exemple #3
0
def decrypt_vote_tally_threshold(public_key, shares, vote_tally):
    """
    Realiza el descifrado de los votos mediante un esquema de cifrado
    umbral.

    .. note:: Idealmente no se reconstruye la clave sino que se usa
        algún protocolo de computación distribuida para ejectuar el
        cómputo **SIN** reconstruir la clave.

    :param public_key: La clave pública de la elección.
    :param vote_tally: El escrutinio cifrado de votos.
    :param shares: Una lista de secretos compartidos que permiten
        descifrar conjuntamente los votos.

    :returns: El escrutinio de votos descifrado.
    """
    private_key = ElGamal.construct((public_key.p, public_key.g, public_key.y, recover_secret(shares)))
    return list(map(lambda x: private_key.decrypt(x), vote_tally))
def test_partial_password(password, p, hashed_secret, work_factor):
    """Check whether the characters supplied are correct for the password"""
    shares = []
    for k, v in password.items():
        key = bcrypt.kdf(password=v.encode('utf-8'),
                         salt=p[k]['salt'],
                         desired_key_bytes=32,
                         rounds=work_factor)
        backend = default_backend()
        cipher = Cipher(algorithms.AES(key),
                        modes.CBC(p[k]['iv']),
                        backend=backend)
        decryptor = cipher.decryptor()
        ct = p[k]['ct'] + (0).to_bytes(16, 'little')
        y = decryptor.update(ct) + decryptor.finalize()
        y = int.from_bytes(y[:16], byteorder='little')
        shares.append((k + 1, y))

    secret = shamir.recover_secret(shares)
    secret = base64.urlsafe_b64encode(secret.to_bytes(16, "little"))
    if bcrypt.checkpw(secret, hashed_secret):
        return True
    else:
        return False
Exemple #5
0
def sock_checker(node_address):
    global total_bytes_received_main

    prev_hop = get_peer(peers, node_address)
    current_channel = get_channel(prev_hop, channels)
    sym_key_prev_hop = prev_hop.sym_key

    while True:

        received_header = json.loads((prev_hop.receive()).decode())
        source = get_peer(peers, received_header['source'])
        commitment_tx = Tx.parse(
            BytesIO(bytes.fromhex(received_header['commitment_tx'])))
        H = check_htlc_and_get_secret_hash(node, commitment_tx,
                                           current_channel)
        num_packets = received_header['num_packets']
        packet_size = received_header['packet_size']
        num_bytes = num_packets * packet_size
        #num_kilobytes = int(num_packets*packet_size/1000)

        prev_hop.send(b'header ACK')

        #receive body
        sym_key_source = source.sym_key

        packet_payloads = []

        for i in range(num_packets):
            packet_payloads.append(prev_hop.receive())
            prev_hop.send(b'packet ACK')

        #decode packets
        decoded_packets = []
        for i in range(len(packet_payloads)):
            decoded_packets.append(
                json.loads(
                    decrypt(packet_payloads[i],
                            sym_key_source.sec()).decode()))

        #get the shares
        if (num_packets == 1):
            revealed_secret = int(decoded_packets[0]['secret_share'])
        else:
            shares = []
            for i in range(len(decoded_packets)):
                shamir_share = decoded_packets[i]['secret_share']
                x, y = map(int, shamir_share.strip('()').split(','))
                shares.append((x, y))

            revealed_secret = shamir.recover_secret(shares)

        #check that you can suceesfully unlock the htlc output
        if (not (H == None)
                and (sha256(str.encode(str(revealed_secret))) == H)):
            print("I can sign the htlc output with the secret")

            #sign the commitment tx
            commitment_tx.tx_ins[0].script_sig = get_script_sig(
                commitment_tx, node.private_key)

            reply = {
                "commitment_tx": str(commitment_tx.serialize().hex()),
                "secret": revealed_secret
            }

            prev_hop.send(str.encode(json.dumps(reply)))

            current_channel.paid(commitment_tx.tx_outs[2].amount)
            print(current_channel)

            total_bytes_received_main += num_bytes
            total_bytes_received.set(total_bytes_received_main)

            wallet_balance = get_total_channel_balance(channels)
            local_balance_CB = get_channel_balance(channels[0])
            local_balance_CD = get_channel_balance(channels[1])

            totalBalance.set(wallet_balance)
            channel_B_local.set(local_balance_CB)
            channel_D_local.set(local_balance_CD)

            print("Total Balance: " + str(get_total_channel_balance(channels)))

        else:
            print("Cannot unlock HTLC")
Exemple #6
0
assert pt2 != None
print(pt2)

# Part 3

N = 3213876088517980551083924185487283336189331657515992206038949
e = 65537
c = 2941293819923490843589362205798232424837846370982721175905966

# From factordb
p = 1267650600228229401496703205653
q = 2535301200456458802993406410833
assert p * q == N

phi = (p - 1) * (q - 1)
d = cun.inverse(e, phi)
pt3 = pow(c, d, N)
pt3 += 541893472927304311696017462663852715895951883676838007787557872016428 * N
pt3 = cun.long_to_bytes(pt3).decode()
print(pt3)

# ---

a = eval(pt1)
b = eval(pt2)
c = eval(pt3)

res = shamir.recover_secret([a, b, c], prime=cun.getPrime(512))
print(cun.long_to_bytes(res).decode())
Exemple #7
0
def recover_secret(shares):
    """
	:param shares: list of points as following: [(server number, server number),...,(server number, server number)]
	:return: the msg as int. this function doesn't check if the msg is valid.
	"""
    return shamir.recover_secret(shares, PRIME)