Socket服务端与客户端加密通信

客户端:

# -*- coding: utf-8 -*-
# @Time    : 2018/2/19 14:15
# @Author  : Xifeng2009

import socket
import time

from Crypto.Cipher import AES

# s_host = '192.168.100.111'
s_host = '127.0.0.1'
s_port = 1337
c_host = '127.0.0.1'
c_port = 1338
timeout = 300

def cmdRECVer():

    command = c.recv(4096)
    print command
    cypher = AES.new('keykey0123456789', AES.MODE_CFB, 'vivivi0123456789')
    command = cypher.decrypt(command)
    print "Decrypting Complete..."
    print command
    c.close()

while True:

    c = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    c.bind((c_host, c_port))

    try:
        c.connect((s_host, s_port))
        print "Connect...Success...%s: %s" % (s_host, s_port)
    except:
        print "Connect...Failed..."
        time.sleep(timeout)
        continue
    try:
        cmdRECVer()
    except socket.error as err:
        print err

服务端:

# -*- coding: utf-8 -*-
# @Time    : 2018/2/19 15:47
# @Author  : Xifeng2009

import socket
from Crypto.Cipher import AES


s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('127.0.0.1', 1337))
s.listen(5)

def command_sender(msg, client):

    # msg must be 16 bytes
    cypher = AES.new('keykey0123456789', AES.MODE_CFB, 'vivivi0123456789')
    cypher = cypher.encrypt(msg)
    client.send(cypher)
    client.close()

while True:
    print "Start Listening..."
    client, addr = s.accept()
    print "Requst from: %s: %s" % (addr[0], addr[1])
    # SEND
    print ">>>",
    msg = raw_input()
    command_sender(msg, client)

猜你喜欢

转载自blog.csdn.net/qq_31017793/article/details/79339800