コード例 #1
0
ファイル: DHEtest.py プロジェクト: e-ht/pyDHE
    def test_Alice_Bob_Same_Key(self):
        for i in range(100):
            # 100 iterations should test well despite randomness?
            alice = pyDHE.new()
            bob = pyDHE.new()
            alice.update(bob.getPublicKey())
            bob.update(alice.getPublicKey())

            self.assertEqual(bob.getFinalKey(), alice.getFinalKey(),
                             "Alice and Bob have different keys")
コード例 #2
0
ファイル: DHEtest.py プロジェクト: e-ht/pyDHE
    def test_negotiate(self, group=14):

        server = socket.socket()
        server.bind(('', 0))
        server.listen(1)
        port = server.getsockname()[1]

        pid = os.fork()

        # child process - aka, the server
        if pid == 0:
            sock, _ = server.accept()
            server.close()

        # parent - aka, the client
        else:
            sock = socket.socket()
            sock.connect(('', port))
            server.close()

        alice = pyDHE.new(group)
        local_key = alice.negotiate(sock)
        #sock.close()

        if pid == 0:
            sock.send(long_to_bytes(local_key))
            sock.close()
        else:
            os.wait()
            remote_key = bytes_to_long(sock.recv(1024))
            sock.close()
            self.assertEqual(local_key, remote_key, "keys do not match")
コード例 #3
0
ファイル: server.py プロジェクト: Rentheus/Messenger
def debug_handshake(userlist, connection, passwd_db):
    truth_value = False
    alice = pyDHE.new()
    value = alice.negotiate(connection)
    e = encr(value)
    print(1)

    username_recv = e.decrypt(connection.recv(1024))
    time.sleep(0.13)
    print(2)
    passwd_recv = e.decrypt(connection.recv(1024))
    print(3)
    #print(username_recv)
    username_parts = username_recv.decode().split(":")
    passwd_parts = passwd_recv.decode()
    print(passwd_parts)

    if passwd_db.add_user(username_parts[1], passwd_parts) == True:
        truth_value = True
        print(1)
    elif passwd_db.check_password(username_parts[1], passwd_parts) == True:
        truth_value = True
        print(2)

    if username_parts[0] == "Username" and truth_value == True:
        userlist.append(username_parts[1])
        connection.send("1:Username Accepted".encode())
        passwd_parts = []
        return e
    else:
        connection.send("0:Authentification failed".encode())
        debug_handshake(userlist, connection, password_db)
コード例 #4
0
 def negotiate(self):
     self.dh = pyDHE.new(14)
     self.sock.send(long_to_bytes(self.dh.getPublicKey()))
     data = self.sock.recv(1024)
     self.dh.update(bytes_to_long(data))
     fullKey = self.dh.getFinalKey()
     self.key = hashlib.sha256((str(fullKey)).encode()).hexdigest()[:32]
     return self.dh.getFinalKey()
コード例 #5
0
    def send_public_key(self, dst):

        User = pyDHE.new()
        msg = str(User.getPublicKey())

        self.NETIF.send_msg(dst, msg.encode('utf-8'))

        return User
コード例 #6
0
    def get_DH(self,data, conn):
        dh = pyDHE.new(14)
        client_public_key = bytes_to_long(data)
        final_key_dh = dh.update(client_public_key)

        my_public_key = dh.getPublicKey()
        conn.send(long_to_bytes(my_public_key))
        self.key = hashlib.sha256((str(final_key_dh)).encode()).hexdigest()[:32]
コード例 #7
0
ファイル: client.py プロジェクト: Veleth/Thesis
 def negotiate(self):
     """
     Negotiates a Diffie-Hellman key with the server
     """
     self.secret = pyDHE.new()
     self.sharedSecret = self.secret.negotiate(self.sock)
     salt = str(self.sock.getsockname()).encode()
     self.key = hashlib.pbkdf2_hmac('sha256', str(self.sharedSecret).encode(), salt, 100000)
コード例 #8
0
def on_connect():
	global Alice, pkey, Alice_server, pkey_server, credentials

	Alice = pyDHE.new()
	pkey = Alice.getPublicKey()
	while not mem_client.get('username') or not mem_client.get('password'):
		time.sleep(5)
		#continue
	print(' connection established ')
	credentials['username'] = mem_client.get('username').decode('utf-8')
	credentials['password'] = mem_client.get('password').decode('utf-8')
	sio.emit('authenticate', credentials)
	mem_client.set('connection',"Connection Successfully Established")
コード例 #9
0
def DH_Original(group):
    # 根据int型group自动选择素数和本原根并生成DHE对象及公私钥对

    DH_Object = pyDHE.new(group)

    print("正在生成本机DH公私钥...")
    DH_PublicKey = DH_Object.getPublicKey()
    # 生成公钥
    DH_PrivateKey = DH_Object.a
    # 生成私钥

    print("本机DH公钥:", str(DH_PublicKey)[0:20])
    print("本机DH私钥:", str(DH_PrivateKey)[0:20])

    return DH_Object, DH_PrivateKey, DH_PublicKey
コード例 #10
0
def debug_handshake(username, passw, socket):
    bob = pyDHE.new()
    value = bob.negotiate(socket)
    e = encr(value)
    
    
    socket.send(e.encrypt(("Username:"******""
    response = socket.recv(1024).decode()
    print("test")
    if response.split(":")[0] == "0":
        debug_handshake(username, passw, socket)
    else:
        return e
コード例 #11
0
def on_connect():
    global dhe_helper, x, credentials

    #diffie hellman keys between each pair of participating clients
    #more info on pyDHE module - https://github.com/deadPix3l/pyDHE
    dhe_helper = pyDHE.new()

    # x = G^a mod P
    x = dhe_helper.getPublicKey(
    )  #public key - generated using common public key and own private key
    #keep on waiting till login credentials are received
    while not mem_client.get('username') or not mem_client.get('password'):
        time.sleep(5)
        #continue
    print(' connection established ')
    credentials['username'] = mem_client.get('username').decode('utf-8')
    credentials['password'] = mem_client.get('password').decode('utf-8')

    #only authorized clients are able to access the main model
    sio.emit('authenticate', credentials)
    mem_client.set('connection', "Connection Successfully Established")
コード例 #12
0
def generate_dh():
    """Generates a DHE object (private)."""
    private_key = pyDHE.new()
    return private_key
コード例 #13
0
ファイル: DHEtest.py プロジェクト: e-ht/pyDHE
 def test_Forgot_update_fail(self):
     self.assertRaises(ValueError, pyDHE.new().getFinalKey)
コード例 #14
0
import pyDHE

alice = pyDHE.new(group=14)
alicePubkey = alice.getPublicKey()
print('Alice pub key:', alicePubkey)

bob = pyDHE.new(group=14)
bobPubkey = bob.getPublicKey()
print('Bob pub key:', bobPubkey)

print('Exchange over Internet...done')

aliceSharedkey = alice.update(bobPubkey)
print('Alice shared key:', hex(aliceSharedkey))

bobSharedKey = bob.update(alicePubkey)
print('Bob shared key:', hex(bobSharedKey))
コード例 #15
0
ファイル: client.py プロジェクト: jai2033shankar/pyChat
from datetime import datetime
from message import Message
from streaming import createMsg, streamData, initializeAES
import pyDHE
import eel

# this is temporary, just for debuggining when you want to open two clients on one computer
# Note that there is a small chance the random port numbers will be the same and crash anyway.
import random

# [GLOBAL VARIABLES]
client = None  # so we can use it in exposed functions
eel.init('./GUI/web')  # initializing eel
eelPort = 42069  # default GUI port

clientDH = pyDHE.new()  # diffiehellman object

# contains names only of all the clients connected
client_list = []


class Client:
    def __init__(self, server_ip, port, client_ip):
        self.SERVER_IP = server_ip
        self.PORT = port
        self.CLIENT_IP = client_ip
        self.finalDecryptionKey = None

        print(f"[*] Host: {self.CLIENT_IP} | Port: {self.PORT}")

        self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
コード例 #16
0
ファイル: crackDHE.py プロジェクト: yashraj0077/Snippets
#!/usr/bin/env python

import pyDHE

alice = pyDHE.new((2, 541))
bob = pyDHE.new((2, 541))

A = alice.getPublicKey()
B = bob.getPublicKey()

K = alice.update(B)
assert K == bob.update(A)

p, g = alice.p, alice.g
a, b = alice.a, bob.a

print('''
Welcome to DiffieCrack!
-----------------------
The goal is to mathematically discover just one of the 
three numbers in the private section, using only public
and inferred (i.e Only what Eve can see). Feel free to 
add more equations to the inferred, but remember:

Don't use any private values. Good Luck!
''')

print('''
Private
--------
a: {}
コード例 #17
0
from datetime import datetime
from message import Message
from streaming import streamData, initializeAES
import pyDHE
import eel

# Importing Random just for Debugging when we want to open two clients on one computer
# there is a very small chance the random port numbers will be the same and crash anyway.
import random

# [GLOBAL VARIABLES]
client = None  # so we can use it in exposed functions
eel.init('./GUI/web')  # Initializing eel
eelPort = 42069  # default GUI port

clientDH = pyDHE.new()  # Diffie-Hellman object

# contains names only of all the clients connected
client_list = []


class Client:
    def __init__(self, server_ip, port, client_ip):
        self.SERVER_IP = server_ip
        self.PORT = port
        self.CLIENT_IP = client_ip
        self.finalDecryptionKey = None

        print(f"[*] Host: {self.SERVER_IP} | Port: {self.PORT}")

        self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
コード例 #18
0
import socketio
import time
import json
import numpy as np
import pyDHE
import retry
from flserver import FLServer
import pandas as pd
from keras.models import model_from_json

NO_OF_ROUNDS = 2

sio = socketio.Server(async_mode='eventlet')
app = socketio.Middleware(sio)

Bob = pyDHE.new(18)
pkey = Bob.getPublicKey()

count_clients = 0
count_rounds = 0
count_auth_clients = 0
conn_threshold = 3
update_threshold = 3
updates_received = 0
client_updates = {}
server_wait_time = 5
suv_dictionary = {}
count_train_done = 0
count_shared_done = 0
fin_weights_str = retry.model_weights_json
fin_struct = retry.model_json
コード例 #19
0
def exchange_key(connection, pub_key):
    """
    Get RSA key from server
    :param connection: Connection to server
    :param pub_key: Client's public key
    :return: server_pub_key, server_pub_key_bytes, max_message_size
    """

    if main.diffe_key_exchange is False:
        # Get the server's public key
        server_pub_key_bytes = connection.recv(1024)

        # Send public key
        connection.sendall(rsa.PublicKey.save_pkcs1(pub_key))

    else:
        # Rounds of bit-shifting and XOR
        rounds = 64

        while True:

            # Generate 4096-bit keys (RFC 3526 Group 16)
            client_diffe_key = pyDHE.new(16)
            shared_secret = client_diffe_key.negotiate(connection)

            # Encrypt
            encrypted = int(
                binascii.hexlify(rsa.PublicKey.save_pkcs1(pub_key)).decode(),
                16)
            for x in range(0, rounds):
                encrypted = encrypted ^ (shared_secret**rounds)
                encrypted = encrypted << rounds
            encrypted = int(str(encrypted)[::-1])

            # Decrypt
            decrypted = encrypted
            decrypted = int(str(decrypted)[::-1])
            for x in range(rounds, 0, -1):
                decrypted = decrypted >> rounds
                decrypted = decrypted ^ (shared_secret**rounds)

            # Check if able to decrypt
            try:
                binascii.unhexlify(hex(decrypted)[2:]).decode()
                client_success = True

            # Generate new keys upon failure and try again
            except UnicodeDecodeError:
                client_success = False
                pass
            except binascii.Error:
                client_success = False
                pass

            # Notify client about encryption status
            server_success = connection.recv(1024)
            if client_success is False:
                connection.send(b'DHE')
            else:
                connection.send(b'CONTINUE')

            # Get encryption status from client
            if client_success is False or server_success == b'DHE':
                pass
            elif server_success == b'CONTINUE':
                break

        # Hold encrypted server key
        server_encrypted = b''

        # Receive encrypted key from the server
        while True:
            data = connection.recv(8192)
            if data == b'ENDED':
                break
            elif data[-5:] == b'ENDED':
                server_encrypted += data[:-5]
                break
            server_encrypted += data

        # Send the encrypted key to the server
        connection.sendall(bytes(hex(encrypted).encode()))
        connection.send(b'ENDED')

        # Decrypt the client's public key
        decrypted = int(server_encrypted, 16)
        decrypted = int(str(int(decrypted))[::-1])
        for x in range(rounds, 0, -1):
            decrypted = decrypted >> rounds
            decrypted = decrypted ^ (shared_secret**rounds)

        server_pub_key_bytes = binascii.unhexlify(hex(decrypted)[2:]).decode()

    server_pub_key = rsa.PublicKey.load_pkcs1(server_pub_key_bytes)
    # Determine max message size
    max_message_size = common.byte_size(server_pub_key.n) - 11

    # Return crypto key information
    return server_pub_key, server_pub_key_bytes, max_message_size
コード例 #20
0
import socket
import threading
import argparse
import os
from datetime import datetime
from message import Message
from streaming import createMsg, streamData, initializeAES, decryptMsg, returnVector
from clientConnectionObj import ClientConnection
import pyDHE
import time

serverDH = pyDHE.new()  # DiffieHellman object


class Server:
    def __init__(self, ip, port):
        self.IP = ip
        self.PORT = port

        self.USERNAME = "******"

        self.temp_f = False  # flag for loop logic

        # holds a list of client connection objects (eventually we should have just this)
        self.clientConnections = []

        self.current_chat = "./logs/currentchat.txt"

        self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)