Beispiel #1
0
from binascii import hexlify
from DiffieHellman import DiffieHellman

a = DiffieHellman()
b = DiffieHellman()

a.genKey(b.publicKey)
b.genKey(a.publicKey)

#a.showParams()
#a.showResults()
#b.showParams()
#b.showResults()

if(a.getKey() == b.getKey()):
    print("Shared keys match.")
    print("Key:", hexlify(a.key))
else:
    print("Shared secrets didn't match!")
    print("Shared secret A: ", a.genSecret(b.publicKey))
    print("Shared secret B: ", b.genSecret(a.publicKey))
Beispiel #2
0
class UserChat:
    def __init__(self, state):
        self.state = state
        self.dh = DiffieHellman()

    def handleMsg(self, resp):
        header = resp.split(';')[0]
        if header == 'e':
            self.state = 'lead'
            raise toSChatError(resp.split(';')[1])
        if self.state == 'syn':
            self.handleOkResp(resp)
        if self.state == 'wait':
            #self.handleSynReq(resp)
            raise SChatError('Unknown Error')
        if self.state == 'okSent':
            self.handleGrResp(resp)

    def handleSynReq(self, resp, serverKey):
        header = resp.split(';')[0]
        if header != 'h':
            raise SChatError(
                'Got invalid msg(header) while in \'wait\' state!')
        try:
            token, self.encData = resp.split(';')[1:]
            return binascii.unhexlify(
                AESCipher(serverKey).decrypt(token)).split(
                    ';')  #username,sharedKey
        except Exception as err:
            raise SChatError(
                'Invalid content in Hi request, problem with decryption! - ' +
                str(err))

    def sendOkMsg(self, peer):
        self.peer = peer
        dhKey, self.nounce = self.peer.aes.decrypt(self.encData).split(';')
        self.peer.send(
            'o;' +
            self.peer.aes.encrypt(self.nounce + ';' + str(self.dh.publicKey))
        )  #+';'+str(peer.sport)))
        self.dh.genKey(int(dhKey))
        self.peer.aes = AESCipher(binascii.hexlify(self.dh.getKey()))
        self.state = 'okSent'

    def handleGrResp(self, resp):
        #expect the next message (g - ack)
        header = resp.split(';')[0]
        if header != 'g':
            raise SChatError(
                'Got invalid msg(header) while in \'okSent\' state!')
        recvNounce = int(self.decryptAes(resp.split(';')[1]))
        if recvNounce != int(self.nounce) + 1:
            raise SChatError(
                'Received nounce sent back by the peer isn\'t compatible with the\n nounce number sent originally by you... \nYou may be under attack if this error continue to apper!'
            )
        self.state = 'ready'

    def decryptAes(self, msg):
        try:
            return self.peer.aes.decrypt(msg)
        except Exception as er:
            raise SChatError(
                'Invalid msg, can\'t decrypt the data, maybe wrong key or unauthorized source! - '
                + str(er))

    def handleOkResp(self, respAddr):
        resp = respAddr[0]
        addr = respAddr[1]
        header = resp.split(';')[0]
        if header != 'o':
            raise SChatError('Got invalid msg(header) while in \'syn\' state!')
        nounce, DHKey = self.decryptAes(resp.split(';')[1]).split(';')
        self.peer.changePort(addr[1])
        self.dh.genKey(int(DHKey))
        self.peer.aes = AESCipher(binascii.hexlify(self.dh.getKey()))
        if nounce != self.nounce:
            raise SChatError(
                'Received nounce sent back by the peer isn\'t compatible with the\n nounce number sent originally by you... \nYou may be under attack if this error continue to apper!'
            )
        self.peer.send('g;' + self.peer.aes.encrypt(str(int(self.nounce) + 1)))
        #self.peer.send('g;' + self.peer.aes.encrypt(str(int(self.nounce) + 1)))
        self.state = 'ready'

    def sendSyn(self, peer, token):
        self.peer = peer
        if self.state != 'lead':
            raise SChatError(
                'Can\'t start chat without getting info from the server about the unknown user!'
            )
        self.nounce = str(randint(1, 65555))
        self.peer.send(
            'h;' + token + ';' +
            self.peer.aes.encrypt(str(self.dh.publicKey) + ';' + self.nounce))
        self.state = 'syn'
Beispiel #3
0
    return data


while True:
    try:
        #        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock = socket.create_connection((TCP_IP, TCP_PORT), 10)
        a = DiffieHellman()
        msg = b64encode(str(a.publicKey).encode())
        sys.stdout.flush()
        print("Len: ", len(msg))
        sock.sendall(msg)
        m = recvall(sock, 2468)
        msg = b64decode(m)
        print("Alice Pub: ", str(a.publicKey))
        a.genKey(int(msg))
        a.showResults()

        print("Key {}".format(a.key))
        aes = AESCipher(a.key)

        f = open('script.txt')
        count = 0
        for line in f:
            if count % 2 == 0:
                ciphertext = aes.encrypt(line)
                sock.sendall(ciphertext)
                print("Sending: {}".format(line))
            else:
                data = aes.decrypt(sock.recv(4096))
                print("Recvd {}".format(data))
Beispiel #4
0
server.bind((TCP_IP, TCP_PORT))
server.listen(1)

print("Listening on {}:{}".format(TCP_IP, TCP_PORT))
sys.stdout.flush()


while True:
    try:
        alice, addr = server.accept()

        data = b64decode(alice.recv(4096).decode()) # buffer size is 1024 bytes
        a = DiffieHellman()
        msg = b64encode(str(a.publicKey).encode())
        alice.sendall(msg)
        a.genKey(int(data))

        bob = socket.create_connection((bob_ip, bob_port), 30)
        b = DiffieHellman()
        msg = b64encode(str(b.publicKey).encode())
        bob.sendall(msg)
        msg = b64decode(bob.recv(4096).decode())
        b.genKey(int(msg))
        
        aes_a = AESCipher(a.key)
        aes_b = AESCipher(b.key)

        while True:
            data = aes_a.decrypt(alice.recv(4096))
            print("Alice Message: {}".format(data))
Beispiel #5
0
            sys.stdout.flush()
            conn, addr = sock.accept()
            m = recvall(conn, 2468)
            #            m = conn.recv(10000).decode()
            print("Recvd: ", m)
            print("Len: ", len(m))
            sys.stdout.flush()
            data = b64decode(m)  # buffer size is 1024 bytes
            print("Recved pub key")
            sys.stdout.flush()

            b = DiffieHellman()
            msg = b64encode(str(b.publicKey).encode())
            conn.sendall(msg)

            b.genKey(int(data))
            print("Generated private key")
            sys.stdout.flush()
            #        ciphertext = conn.recv(4096)

            aes = AESCipher(b.key)

            f = open('script.txt')

            count = 0
            for line in f:
                #            print("In loop")
                if count % 2 == 1:
                    ciphertext = aes.encrypt(line)
                    conn.sendall(ciphertext)
                    print("Sending {}".format(line))