如何使用AES加密字符串并使用python中的服务器和客户端在python中解密字符串

时间:2019-06-16 12:03:07

标签: python encryption server aes

我正在使用Python 3.7。 我的目标是创建一个服务器,该服务器将以AES加密方式使用密钥(服务器和客户端均具有“密钥”)对随机字符串进行加密。服务器将把密码发送给客户端,客户端将对其解密。

但是,我编写的代码没有显示任何结果。我的意思是,代码被“避免”了,我看不到代码的任何结果。 这是我编写的代码(服务器和客户端):

服务器:

import socket
import Crypto
import Cryptodome


HOST = '127.0.0.1'  # Standard loopback interface address (localhost)
PORT = 8080        # Port to listen on (non-privileged ports are > 1023)


s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
print ('Socket binded to port 8080')
s.listen(0)
print ('socket is listening')

while True:
   c, addr = s.accept()
   print ('Got connection from ', addr)
   string = str(c.recv(1024))
   print(string)
   if string ==  "b'Register'" :
       import random
       import string


       def randomString(stringLength=10):
           letters = string.ascii_lowercase
           return ''.join(random.choice(letters) for i in range(stringLength))
       print("Random String is ", randomString())

       from Crypto.Cipher import AES

       from Crypto.Cipher import AES


       def do_encrypt(message):
           obj = AES.new('This is a key123', AES.MODE_CBC, 'This is an IV456')
           ciphertext = obj.encrypt(message)
           return ciphertext

客户:


import socket

HOST = '127.0.0.1'                         # The server's hostname or IP address
PORT = 8080                                # The port used by the server



import Crypto
import sys
sys.modules['Crypto'] = Crypto


name = ''                                          # Sign in to the server!!

while name != 'Register':
   print('Would you like to Register/Login?')
   name = input()

s = socket.socket()
port = 8080
s.connect(('localhost', port))
z = 'Register'
s.sendall(z.encode())
s.close()
name = ''                                          # Sign in to the server!!

print ("Register request sent")




from Crypto.Cipher import AES

def do_decrypt(ciphertext):
    obj2 = AES.new('This is a key123', AES.MODE_CBC, 'This is an IV456')
    message = obj2.decrypt(ciphertext)
    return message






from Crypto.PublicKey import RSA

key = RSA.generate(2048)                             # Private key creation
private_key = key.export_key()
file_out = open("private.txt", "wb")
file_out.write(private_key)

public_key = key.publickey().export_key()            # Public key creation
file_out = open("receiver.txt", "wb")
file_out.write(public_key)

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:   # sending the Public key to the server.
   s.connect((HOST, PORT))
   s.sendall(public_key)
   data = s.recv(1024)
   s.close()                                       # Close the socket when done

   print('Received', repr(data))

AES加密代码的来源:Sending Encrypted strings using socket in Python

1 个答案:

答案 0 :(得分:0)

您没有得到与AES加密代码相关的任何信息,因为您没有调用该函数。