예제 #1
0
파일: client.py 프로젝트: Monica-y/Monica
def socket_client():
    serverName = '127.0.0.1'
    serverPort = 11000
    BUFSIZ = 1024
    ADDR = (serverName, serverPort)
    # 套接字家族可以使 AF_UNIX 或者 AF_INET。
    # 套接字类型可以根据是面向连接的还是非连接分为 SOCK_STREAM 或 SOCK_DGRAM。
    clientSocket = socket(AF_INET, SOCK_STREAM)
    # 主动初始化TCP服务器连接。
    # 一般address的格式为元组(hostname,port),如果连接出错,返回socket.error错误。
    clientSocket.connect(ADDR)
    print(clientSocket.recv(BUFSIZ))
    data = clientSocket.recv(BUFSIZ)
    str_data = bytes.decode(data)
    # p_g_public
    begin = 0
    keyword = ['', '', '']
    cnt = 0
    for index in range(len(str_data)):
        if str_data[index] == 'A' or index == len(str_data) - 1:
            if (index == len(str_data) - 1):
                index = index + 1
            for i in range(begin, index):
                keyword[cnt] = keyword[cnt] + str_data[i]
            cnt = cnt + 1
            begin = index + 1
    client = DH(int(keyword[0]), int(keyword[1]))
    client.calculateAESKey(int(keyword[2]))
    clientSocket.send(str(client.send_to_other_key).encode())
    print(clientSocket.recv(BUFSIZ))
    print('The client\'s AES key seed is ' + str(client.AES_key))
    Clientmd5 = MD5(str(client.AES_key))
    key = Clientmd5.md5Encode()
    print('The client\'s AES key is ' + key)
    while True:
        filepath = input("please input file path:")
        if os.path.isfile(filepath):
            # 定义定义文件信息。128s表示文件名为128bytes长,l表示一个int或log文件类型,在此为文件大小
            fileinfo_size = struct.calcsize('128sl')
            # 定义文件头信息,包括文件名和文件大小
            datalen = getlen(filepath, key)
            # fhead = struct.pack('128sl',os.path.basename(filepath).encode('utf-8'),
            # os.stat(filepath).st_size)
            fhead = struct.pack('128sl',
                                os.path.basename(filepath).encode('utf-8'),
                                datalen)
        if os.path.isfile(filepath):
            clientSocket.send(fhead)
            print('client filepath:{0}'.format(filepath))
            fp = open(filepath, 'rb')
            while True:
                data = fp.read(512)  # 1024的话这里可能会有问题,因为编码后大小会变大
                if not data:
                    print('{0} file send over...'.format(filepath))
                    fp.close()
                    break
                data = AES(key, bytes.decode(data), ENCRYPT)
                clientSocket.send(data.encode())
    # 因为如果传输完数据就关闭client,那么server那里会报错,因此使用死循环让client不能断开,这样server就不会报错了
    clientSocket.close()
예제 #2
0
def deal_data(conn, addr):
    print('Accept new connection from{0}'.format(addr))
    conn.send('Welcome to the server!Let\'s exchange the key'.encode('utf-8'))
    p, g = find_pg()
    Server = DH(p, g)
    p_g_publicKey = str(p) + 'A' + str(g) + 'A' + str(Server.send_to_other_key)
    conn.send(p_g_publicKey.encode())
    conn.send('Server\'s public key send over'.encode())
    data = conn.recv(1024)
    public_key = int(data)
    Server.calculateAESKey(public_key)
    conn.send('key exchange completed'.encode())
    print('The server\'s AES key seed is ' + str(Server.AES_key))
    Servermd5 = MD5(str(Server.AES_key))
    key = Servermd5.md5Encode()
    print('The server\'s AES key is ' + key)
    # while True:
    fileinfo_size = struct.calcsize('128sl')
    buf = conn.recv(fileinfo_size)
    if buf:
        filename, filesize = struct.unpack('128sl', buf)
        if filesize % 16 != 0:
            filesize = filesize + 16  # 因为AES加密会填充够16个
            filesize = int(floor(filesize / 16) * 16)
        fn = filename.strip('\00'.encode('utf-8'))
        strfn = str(fn, 'utf-8')
        new_filename = os.path.join('F:\\py-test\\key_exchange\\' +
                                    'receive_' + strfn)
        print('file new name is{0},filesize is{1}'.format(
            new_filename, filesize))
        # 记录已接收文件的大小
        recvd_size = 0
        fp = open(new_filename, 'wb+')
        print('start receiving')

        while True:
            # 可能会碰到ConnectionResetError [WinError 10054] 远程主机强迫关闭了一个现有的连接。这是因为client已经发完数据并关闭了连接造成的
            data = conn.recv(1024)
            if not data:
                print('end receive...')
                break
            data = AES(key, bytes.decode(data), DECRYPT)  # 在这里加上解密
            print(data)
            recvd_size = recvd_size + len(data)
            fp.write(data.encode())
            if recvd_size >= filesize:
                break
        fp.close()
        print('end receive...')
        # conn.send('receive successfully'.encode())
    conn.close()
예제 #3
0
파일: getlen.py 프로젝트: Monica-y/Monica
def getlen(filepath, key):
    filelen = 0
    if os.path.isfile(filepath):
        fp = open(filepath, 'rb')
        while True:
            data = fp.read(512)  # 1024的话这里可能会有问题,因为编码后大小会变大
            if not data:
                print('{0} End of encrypted file size calculation...'.format(
                    filepath))
                fp.close()
                break
            data = AES(key, bytes.decode(data), ENCRYPT)
            filelen = filelen + len(data.encode())
    # print(filelen)
    return filelen
예제 #4
0
파일: client.py 프로젝트: Monica-y/Monica
def socket_client():
    serverName = '127.0.0.1'
    serverPort = 11000
    BUFSIZ = 1024
    ADDR = (serverName, serverPort)

    # 套接字家族可以使 AF_UNIX 或者 AF_INET。
    # 套接字类型可以根据是面向连接的还是非连接分为 SOCK_STREAM 或 SOCK_DGRAM。
    clientSocket = socket(AF_INET, SOCK_STREAM)
    # 主动初始化TCP服务器连接。
    # 一般address的格式为元组(hostname,port),如果连接出错,返回socket.error错误。
    clientSocket.connect(ADDR)
    print(clientSocket.recv(BUFSIZ))

    while True:
        # data = "client message"
        # data = input('>>>')
        filepath = input("please input file path:")
        if os.path.isfile(filepath):
            # 定义定义文件信息。128s表示文件名为128bytes长,l表示一个int或log文件类型,在此为文件大小
            fileinfo_size = struct.calcsize('128sl')
            # 定义文件头信息,包括文件名和文件大小
            fhead = struct.pack('128sl',
                                os.path.basename(filepath).encode('utf-8'),
                                os.stat(filepath).st_size)
            clientSocket.send(fhead)
            print('client filepath:{0}'.format(filepath))
            fp = open(filepath, 'rb')
            # fp = open(filepath,'r')
            while True:
                data = fp.read(1024)  # 1024
                # data = AES('1234567890123456',str(data,'utf-8'),ENCRYPT)
                if not data:
                    print('{0} file send over...'.format(filepath))
                    break
                data = AES('1234567890123456', bytes.decode(data), ENCRYPT)
                # clientSocket.send(data.encode('utf-8'))
                clientSocket.send(data.encode())
        # clientSocket.send(data.encode('utf-8'))
        # returnData = clientSocket.recv(BUFSIZ)
        # if not returnData:
        #     break
        # print('Return time is:%s' %returnData.decode('utf-8'))
        clientSocket.close()
예제 #5
0
def deal_data(conn, addr):
    print('Accept new connection from{0}'.format(addr))
    conn.send('Welcome to the server!'.encode('utf-8'))
    while True:
        fileinfo_size = struct.calcsize('128sl')
        buf = conn.recv(fileinfo_size)
        if buf:
            filename, filesize = struct.unpack('128sl', buf)
            fn = filename.strip('\00'.encode('utf-8'))
            strfn = str(fn, 'utf-8')
            # new_filename = os.path.join('./','receive_'+strfn)# fn
            new_filename = os.path.join('F:\\py-test\\' + 'receive_' + strfn)
            # "C:\Users\孙玉琪\receive_info.txt"
            print('file new name is{0},filesize is{1}'.format(
                new_filename, filesize))
            # 记录已接收文件的大小
            recvd_size = 0
            # fp = open(new_filename,'wb')
            fp = open(new_filename, 'wb+')
            print('start receiving')

            while True:
                data = conn.recv(1024)
                if not data:
                    print('end receive...')
                    break
                # data = AES('1234567890123456',str(data,'utf-8'),DECRYPT)# 在这里加上解密
                data = AES('1234567890123456', bytes.decode(data),
                           DECRYPT)  # 在这里加上解密
                print(data)
                recvd_size = recvd_size + len(data)
                # fp.write(data.encode('utf-8'))
                fp.write(data.encode())
            fp.close()
            print('end receive...')
        conn.close()
        break
예제 #6
0
파일: getlen.py 프로젝트: Monica-y/Monica
from AES import ENCRYPT
from AES import AES


def getlen(filepath, key):
    filelen = 0
    if os.path.isfile(filepath):
        fp = open(filepath, 'rb')
        while True:
            data = fp.read(512)  # 1024的话这里可能会有问题,因为编码后大小会变大
            if not data:
                print('{0} End of encrypted file size calculation...'.format(
                    filepath))
                fp.close()
                break
            data = AES(key, bytes.decode(data), ENCRYPT)
            filelen = filelen + len(data.encode())
    # print(filelen)
    return filelen


if __name__ == '__main__':
    len1 = getlen("F:\\py-test\\key_exchange\\history.txt", '1234567890123456')
    print(len1)
    res = AES(
        '1234567890123456',
        'Rather than building all of its functionality into its core, Python was designed to be highly extensible via modules. This compact modularity has made it particularly popular as a means of adding programmable interfaces to existing applications. Van Rossum\'s vision of a small core language with a large standard library and easily extensible interpreter stemmed from his frustrations with ABC, which espoused the opposite approach.Rather than building all of its functionality into its core, Python was designed to be highly extensible via modules. This compact modularity has made it particularly popular as a means of adding programmable interfaces to existing applications. Van Rossum\'s vision of a small core language with a large standard library and easily extensible interpreter stemmed from his frustrations with ABC, which espoused the opposite approach.Rather than building all of its functionality into its core, Python was designed to be highly extensible via modules. This compact modularity has made it particularly popular as a means of adding programmable interfaces to existing applications. Van Rossum\'s vision of a small core language with a large standard library and easily extensible interpreter stemmed from his frustrations with ABC, which espoused the opposite approach.Rather than building all of its functionality into its core, Python was designed to be highly extensible via modules. This compact modularity has made it particularly popular as a means of adding programmable interfaces to existing applications. Van Rossum\'s vision of a small core language with a large standard library and easily extensible interpreter stemmed from his frustrations with ABC, which espoused the opposite approach.',
        ENCRYPT)
    data = res.encode()
    len2 = len(data)
    print(len2)