Use Python's Crypto module which supports AES. You need a symmetric key (same key used to encrypt and decrypt). The same key can be generated in both server and client if the same passphrase and the initialization vector(IV) are used.

Summary: 1. Same key to be used to encrypt and decrypt 2. Use Crypto.Cipher.AES

AES has methods to generate key, encrypt and decrypt data. Following links have the actual code. pycrypto stackoverflow

Client - Call this method to encrypt your data and send the encrypted data

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

Server - Receive data and call this method to decrypt the data

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

This is a sample code, make sure you choose a strong passphrase and IV.

Answer from helloV on Stack Overflow
🌐
Stack Overflow
stackoverflow.com › questions › 70493219 › how-do-i-achieve-python-tcp-socket-client-server-with-communications-encrypted
How do I achieve Python TCP Socket Client/Server with Communications Encrypted? - Stack Overflow
(2) And how am I supposed to encrypt/decrypt the communication properly and efficiently? (It'd be nice to see code solutions with explanation, many thanks) ... import socket import os from _thread import * import struct # Here to convert Python data types into byte streams (in string) and back # ---- To Avoid Message Boundary Problem on top of TCP protocol ---- def send_msg(sock: socket, msg): # ---- Use this to send # Prefix each message with a 4-byte length (network byte order) msg = struct.pack('>I', len(msg)) + msg sock.sendall(msg) def recv_msg(sock: socket): # ---- Use this to receive #
🌐
DenizHalil
denizhalil.com › home › blogs › communicating with python sockets using encryption
Python Socket Encryption: Securing Communication in the Digital Age
September 29, 2024 - The main purpose of this project is to create a basic encryption application that securely exchanges messages between a server and a client. The encryption ensures that the data transmitted remains unreadable to anyone who might intercept the ...
🌐
DevTut
devtut.github.io › python › sockets-and-message-encryption-decryption-between-client-and-server.html
Python - Sockets And Message Encryption/Decryption Between Client and Server
To prevent this and converting string public key to rsa public key, we need to write server_public_key = RSA.importKey(getpbk) ,here getpbk is the public key from the client. (SERVER)The next step is to create a session key. Here, I have used “os” module to create a random key “key = os.urandom(16)” which will give us a 16bit long key and after that I have encrypted that key in “AES.MODE_CTR” and hash it again with SHA-1:
🌐
Rip Tutorial
riptutorial.com › sockets and message encryption/decryption between client and server
Python Language Tutorial => Sockets And Message...
To prevent this and converting string public key to rsa public key, we need to write server_public_key = RSA.importKey(getpbk) ,here getpbk is the public key from the client. (SERVER)The next step is to create a session key. Here, I have used “os” module to create a random key “key = os.urandom(16)” which will give us a 16bit long key and after that I have encrypted that key in “AES.MODE_CTR” and hash it again with SHA-1:
🌐
GitHub
github.com › MustafaPatharia › Encrypted-Client-Server-Chat › blob › master › client.py
Encrypted-Client-Server-Chat/client.py at master · MustafaPatharia/Encrypted-Client-Server-Chat
It is a simple program for RSA Cryptography and Digital signature chat. This program offers Encrypted client sever chat which uses the python library for the encryption and decryption.
Author   MustafaPatharia
🌐
GitHub
github.com › condrack › Cryptography-Project-2
GitHub - condrack/Cryptography-Project-2: Python client/server encryption application with mac and hash · GitHub
In order to send the key objects I use python pickles to serialize the keys and convert them back when received. After the server reveives both keys it decrypts them with its private key.
Author   condrack
Find elsewhere
🌐
Pythonpedia
pythonpedia.com › en › tutorial › 8710 › sockets-and-message-encryption-decryption-between-client-and-server
Sockets And Message Encryption/Decryption Between Client and Server | Python Language Tutorial
To prevent this and converting string public key to rsa public key, we need to write server_public_key = RSA.importKey(getpbk) ,here getpbk is the public key from the client. (SERVER)The next step is to create a session key. Here, I have used “os” module to create a random key “key = os.urandom(16)” which will give us a 16bit long key and after that I have encrypted that key in “AES.MODE_CTR” and hash it again with SHA-1:
🌐
GitHub
github.com › mjm918 › python-AES-encryption-socket-secure-chat
GitHub - mjm918/python-AES-encryption-socket-secure-chat
In this case, server will combine ... Client:` As soon as the client receives the keys and hash, it will decrypt with the private key and split the response from server and split them by delimiter (“:”)....
Starred by 13 users
Forked by 7 users
Languages   Python 100.0% | Python 100.0%
🌐
GitHub
github.com › BerntA › SecureChatServer
GitHub - BerntA/SecureChatServer: A simple end-to-end encrypted client/server chat in Python
Run src/chat_server.py to start the server, it utilizes Diffie-Hellman for key exchange, and Simplified DES for symmetric encryption (this can be replaced by DES or AES, etc!). Run src/chat_client.py to create a new chat client, the server will share every client's public key with each other, for now you may only talk one-to-one, but this can easily be extended!
Author   BerntA
🌐
GitHub
github.com › mayankgureja › encryptedChatRSA
GitHub - mayankgureja/encryptedChatRSA: A Chat Server/Client with built-in RSA encryption written in Python
March 16, 2013 - This is a Chat Server/Client with built-in RSA encryption written in Python. This program uses p2p (peer-to-peer) and not full duplex connections.
Starred by 9 users
Forked by 4 users
Languages   Python 100.0% | Python 100.0%
🌐
Stack Overflow
stackoverflow.com › questions › 56618653 › how-to-encrypt-string-with-aes-and-decrypt-it-in-python-with-server-and-client-i
encryption - How to encrypt string with AES and decrypt it in python with server and client in Python - Stack Overflow
June 16, 2019 - 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.wri
🌐
Stack Exchange
security.stackexchange.com › questions › 102058 › best-way-to-implement-secure-client-server-communication-in-python
encryption - Best way to implement secure client/server communication in Python - Information Security Stack Exchange
October 6, 2015 - The client program will then generate its own file, call it 'client_file', and then must be able to send commands to the server (e.g. create new account, set some value, get some value, simple transactional requests). This client_file can be thought of as a client key or PIN that allows the server to know who the user is.
🌐
Awilk54
tech.awilk54.com › 2019 › 02 › python-coding-encrypted-clientserver.html
Python Coding- Encrypted Client/Server TCP Communication
February 11, 2019 - If you would like to review the ... of this assignment was to create a client/server program that implemented AES 256-bit encryption to encrypt a secure message between a client and a server....
🌐
Blogger
studyraspberrypi.blogspot.com › 2016 › 01 › sending-rsa-encrypted-message-from.html
Study Raspberry Pi: Sending an RSA encrypted message from client to Python socket server
January 19, 2016 - For the introduction to the Python socket server, refer to this: Connect Mac / iPhone to a Simple Python Socket Server ... Public key sent to client. ... Encrypted message = ('\x9a\xe0\x08\xa1\xb6\x86?\xc7\xde\xb6\xa0\xbe\xa7!\xecem.\xb1R\xc5h\x19cv]{\xd3\x04\xcf\x0e\xf0\xfe\xc50\x1e\xc9U\xff\xd5\xf2\xb1,EQ\xdf2\x89![\xb7s\x84:C\xbdg\xbf$\x05\'\xb8@GK\x18Q\xd5N\xe9\x13\x12e\x8c\xe7F\xc8+\x95\xcdj\xb6\xcc9\xc8-t\x17-\xb8\xdei\x8f\x90\xdd\xcf\xd9@\xa0\xf8\xe8\xe5\xcci\xea"M\x82\xb8%\xf7\xfccc G{\x16A)\xf2\xcb"\x15\xa8\x16\xd3M',) Decrypted message = This is my secret message.
🌐
rohitab.com
rohitab.com › discuss › topic › 39921-python-aes-encrypted-server-client
Python AES Encrypted Server + Client - Programming - rohitab.com - Forums
August 4, 2025 - Hi guys, I've successfully made a Client + Server in Python and so i decided to use pycrypto ( http://www.codekoala...using-pycrypto/ ) to encrypt the data going back and forth. I edit to the server and the client properly and the client connects back to the server fine, However when i try to use any command on the server it throws this : Traceback (most recent call last): File "AESserver.py", line 48, in <module> decrypted = DecodeAES(cipher, data) File "AESserver.py", line 22, in <lambda> DecodeAES = lambda c, e: c.decrypt(base64.b64decode(e)).rstrip(PADDING) File "C:\python27\lib\base64.py", line 76, in b64decode raise TypeError(msg) TypeError: Incorrect padding Can anyone think of any possible reasons for this and/or how to fix ?
🌐
Medium
medium.com › @md.julfikar.mahmud › secure-socket-programming-in-python-d37b93233c69
Secure socket programming in Python | by Mohammad Julfikar | Medium
December 22, 2018 - After receiving the request from client, server will split the request by delimiter and match the public key and hash of the public key. If both of them matches, server concat an eight byte key, session key and server’s public key and encrypt it with the public key from client. After encrypting it, server sends it to client and client decrypt it with it’s own private key.
Top answer
1 of 4
3

Here is a solution, for small letters only. It can easily be modified to handle also capital letters, by adding them to the text strings.

As can be seen, the space character is at the same position in both lists. This is not necessary, as any character can be translated to any other. However if the decrypted or encrypted is not containing unique characters only, the program will break down.

Copydecrypted = b"abcdefghijklmnopqrstuvwxyz "
encrypted = b"qwertyuiopasdfghjklzxcvbnm "

encrypt_table = bytes.maketrans(decrypted, encrypted)
decrypt_table = bytes.maketrans(encrypted, decrypted)

result = ''
choice = ''
message = ''

while choice != '0':
    choice = input("\n Do you want to encrypt or decrypt the message?\n 1 to encrypt, 2 to decrypt or 0 to exit program. ")

    if choice == '1':
        message = input('\nEnter message for encryption: ')
        result = message.translate(encrypt_table)
        print(result + '\n\n')

    elif choice == '2':
        message = input('\nEnter message to decrypt: ')
        result = message.translate(decrypt_table)
        print(result + '\n\n')

    elif choice != '0':
        print('You have entered an invalid input, please try again. \n\n')
2 of 4
1

Ok, so a few things here...

First I'll give you exactly what you were looking for and explain what I used and some of the changes that needed to be made to your original code. Then I'll explain some inherent issues what what you're trying to do and suggest some areas to read up on/some ways you might want to improve what you've got.

Here's the code you're looking for (while retaining the same flow as what you submitted put above):

Copyimport random

result = ''
choice = ''
message = ''

characters_in_order = [chr(x) for x in range(32,127)]

while choice != 0:
    choice = input("\n Do you want to encrypt or decrypt the message?\n 1 to encrypt, 2 to decrypt or 0 to exit program. ")

    if str(choice) == '1':
        message = input('\nEnter message for encryption: ')
        
        r_seed = input('Enter an integer to use as a seed: ')
        random.seed(r_seed)
        shuffled_list = [chr(x) for x in range(32,127)]
        random.shuffle(shuffled_list)

        for i in range(0, len(message)):
            result += shuffled_list[characters_in_order.index(message[i])]

        print(result + '\n\n')
        result = ''

    elif str(choice) == '2':
        message = input('\nEnter message to decrypt: ')

        r_seed = input('Enter an integer to use as a seed (should be the same one used to encrypt): ')
        random.seed(r_seed)
        shuffled_list = [chr(x) for x in range(32,127)]
        random.shuffle(shuffled_list)

        for i in range(0, len(message)):
            result += characters_in_order[shuffled_list.index(message[i])]

        print(result + '\n\n')
        result = ''

    elif str(choice) != '0':
        print('You have entered an invalid input, please try again. \n\n')

You'll notice that I set a global 'characters in order' list, which is just every ASCII character (32-126) in order. I also imported the 'random' module and used this to shuffle the characters in order according to a seed that the user inputs. As long as this seed is the same on the encryption and decryption end, it will produce the same shuffled list and it should work to encrypt or decipher the same string. Also notice the str() around your input choices. Without that, the user had to input '1', rather than 1 to submit a choice without an error.

All of that said...

  1. Notice that the way the new function works is by looking at a character's index in one list and pulling out the character at that index in another. The method you were using, of incrementing or decrementing a character's ASCII code is basic (though not much more basic than this), but it also has a pretty critical flaw, which is that characters on one end or another of the ASCII set wouldn't return ASCII characters. If you were encrypting it at a bit-level, which would be preferred, this wouldn't matter/would be irrelevant, but here you're not going to get the kind of string back that you want if you were to, for example, enter a [space] (ASCII 32) into your plaintext to be encrypted.
  2. If you're interested, you might want to read up on symmetric key encryption/DES for some ideas on how encryption is really done, though props on the start/interest and this can certainly be a fun way to create some sort of cryptogram puzzle or something along those lines. I won't pretend to be any kind of expert, but I can at least point you in the write direction. (https://en.wikipedia.org/wiki/Data_Encryption_Standard https://en.wikipedia.org/wiki/Symmetric-key_algorithm)
  3. Consider having your code read in a .txt file and print out to a .txt file, rather than using user input for the message.

Again, I'm not an expert by any means and there are definitely some fun uses of the kind of program you're aiming for, just trying to point you in the right direction if this is something that you're interested in. Hope all of that is helpful!