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
Now Server and Client switch Ports, and Communicate over there while using the Public key of the other to Encrypt the Messages and decrypt them with their Private key. You can also Hard-code the Public Keys, if you only have one Server and one Client.
๐ŸŒ
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 - However before I get started I wanted to elicit any ideas about the best way to implement this. I was thinking of using the server_file to sign (HMAC) the client_key and send the commands from client to server (along with the transaction message) using something like AES in CTR mode.
Discussions

Sending Encrypted strings using socket in Python - Stack Overflow
I made a simple server program that is able to receive data from 4 different clients at a time. Now I want to send some data with AES-128 Encryption but that should be decoded at the server side. ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
RSA Encrypting through socket programming
Basically, Iโ€™ve got a task to send a message from client to server via assymetric encryption. Iโ€™ve studied some things about RSA and tried to implement it through creating public keys and private keys for server and client. However Iโ€™ve got problems with encoding and encrypting, and I ... More on forum.freecodecamp.org
๐ŸŒ forum.freecodecamp.org
0
0
November 3, 2022
encryption - How to encrypt string with AES and decrypt it in python with server and client in Python - Stack Overflow
I'm using Python 3.7. My goal is to create a server that will encrypt a random string with a key (both the server & client have the "key"), in AES encryption. The server will send the ciphercod... More on stackoverflow.com
๐ŸŒ stackoverflow.com
June 16, 2019
python - How do I encrypt the source code on the webserver? - Software Engineering Stack Exchange
I have a web application developed using Python, HTML, CSS & JavaScript. The customer installs it in any of their own Machine and uses it through their LAN. In short the customer sets up the More on softwareengineering.stackexchange.com
๐ŸŒ softwareengineering.stackexchange.com
January 12, 2012
๐ŸŒ
rohitab.com
rohitab.com โ€บ discuss โ€บ topic โ€บ 39921-python-aes-encrypted-server-client
Python AES Encrypted Server + Client - Programming - rohitab.com - Forums
16 hours ago - 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.
๐ŸŒ
Quora
quora.com โ€บ How-do-you-implement-secure-client-or-server-communication-in-Python
How to implement secure client or server communication in Python - Quora
There are many python modules that allow you to utilise various forms of encryption. Modules such as PyCrypto and PyNaCl (lib sodium) give you an API that lets you employ some powerful cryptography. For example, you could use PyCryptoโ€™s ability ...
Find elsewhere
๐ŸŒ
freeCodeCamp
forum.freecodecamp.org โ€บ python
RSA Encrypting through socket programming - Python - The freeCodeCamp Forum
November 3, 2022 - Basically, Iโ€™ve got a task to send a message from client to server via assymetric encryption. Iโ€™ve studied some things about RSA and tried to implement it through creating public keys and private keys for server and client. However Iโ€™ve got problems with encoding and encrypting, and I always get errors. import socket #file for client import rsa #192.168.1.1 PORT = 2020 HEADER = 2048 DISCONNECT_MESSAGE="!DISCONNECT" SERVER = socket.gethostbyname(socket.gethostname()) client = socket.socket(sock...
๐ŸŒ
Medium
medium.com โ€บ @md.julfikar.mahmud โ€บ secure-socket-programming-in-python-d37b93233c69
Secure socket programming in Python | by Mohammad Julfikar | Medium
December 22, 2018 - We can hard-code the port as 8080 ยท At the same time we will create RSA key for the encryption. We need a public key and private key. Public key will be sent to client and private will be used by server only.
๐ŸŒ
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:
๐ŸŒ
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 - This is the code I wrote (server and client): ... 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 = st
Top answer
1 of 3
20

Once your customer has a program they can run, they will be able to reverse engineer it given sufficient time & skill. That is just a fact of life.

If you really want to stop it, you should host and run the software yourself (SaaS)

Having said that, something like Python will be easier than C. Let's split this into the 3 parts you asked about (and then some more)

HTML

No matter what you do here, it will be decrypted in the browser (even in the SaaS model), so encrypting it on the server is pointless. Even minifying is pointless as modern browsers like Firefox and Chrome will neatly format it for them.

CSS

See above - don't waste your time

Javascript

Yahoo has a tool that can obfuscate it for you. Try YUI Compressor. Not, don't both encrypting this on the server-side as it must be served to the client unecrypted*, which would defeat the purpose.

Python

This is the only place you really want to spend your time - protecting your business logic. There are several methods you will find on google such as encrypting on disk and then decrypting at run-time. All these methods have problems, such as performance hits and having to supply the decrypter (hence enabling them to decrypt it anyone).

Your best beat to stop those not hellbent on stealing your code would be to use an obfuscate your Python code.

Summary

The only code you can stop someone from getting is the code you don't give them. HTML, CSS & Javascript will always end up on your users machine in a manner they can use, so assume they be able to steal it if they want, tough luck.

To protect your server code, the only sure-fire method is to NOT give it to them, running it in something like a SaaS model.

If that isn't possible, the best you can do is make it harder for them.

Testing

Always make sure you test on the production version you will be supplying your customers. This ensures any special build steps (such as obfuscation & minification) do not break your software.

Boring Business Stuff

So all of the above (and your question) has addressed this issue from the technical side. The other side of the coin is from the business/legal side.

If you have a small number of clients you can provide different "watermarked" versions of your software to each client. By doing this, you increase the possibility being able to track stolen software back to the source and take whatever legal action is appropriate.

Don't forgot, if you are in a serious business, you would be best to consult a lawyer on how you can prove and enforce the ownership of your software, should things go wrong.


* not strictly true, you could serve it encrypted and have other Javascript decrypt it on the fly, but this would be near pointless as it adds a performance hit and you will have to supply the attacker with the decrypter anyway...

2 of 3
5

No.

HTMl, CSS, and JavaScript Cannot be encryption as the Browser needs to read it as Plain text. The best you can do is Obfuscate it.

For Python you could compile it into a DLL, so you are not outright giving the client the source code. But is can still be De-compiled.


For Arguments Sake, lets say provided a Custom Web server for your clients to use this Custom Web server reads Encrypted Python files then compiles and runs them. A hacker could still De-compiled the Custom Web server and get full access to the decryption module and the Encryption keys.

If you Code (or data) in any form, is on someone else hardware, The code can be stolen.

My proof of this : Just look at all the warez sites, everything gets hacked.

๐ŸŒ
Awilk54
tech.awilk54.com โ€บ 2019 โ€บ 02 โ€บ python-coding-encrypted-clientserver.html
Python Coding- Encrypted Client/Server TCP Communication
February 11, 2019 - Figure 3. TCP_ClientB.py Client B was created to connect after Client A and to receive the decrypted message from the server that was sent by Client A. Since Client B doesnโ€™t actually do any encrypting/decrypting, the application simply creates a TCP socket to receive data. Running the application yields the following results... 1. First you launch the TCP_Server.py script and the TCP_Client.py script. Figure 4. Figure 5. When you launch Client_A it asks for a secret message to be typed.
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!

๐ŸŒ
Reddit
reddit.com โ€บ r/python โ€บ i created a website to encrypt python so that you can secure your python code
r/Python on Reddit: I created a website to encrypt python so that you can secure your Python code
January 31, 2025 -

GateCode - Secure Your Python Code ๐Ÿ”’

Python's simplicity and flexibility come with a trade-off: source code is easily exposed when published or deployed. GateCode provides a secure solution to this long-standing problem by enabling you to encrypt your Python scripts, allowing deployment without revealing your IP(intellectual property) or secret in the source code.

Website: https://www.gatecode.org/

Key Features ๐Ÿ”

  • Secure Code Encryption: Protect your intellectual property by encrypting your Python scripts.

  • Easy Integration: Minimal effort required to integrate the encrypted package into your projects.

  • Cross-Platform Deployment: Deploy your encrypted code to any environment without exposing its contents.

Video Tutorial

Video Title

Example Use Case ๐Ÿ“Š

Imagine youโ€™ve developed a proprietary algorithm that you need to deploy to your clients. Using GateCode:

  1. Encrypt the Python script containing your algorithm.

  2. Provide the encrypted package to your client.

  3. Your client integrates the package without accessing the original source code.

This ensures that your intellectual property is secure while maintaining usability.

Why GateCode? ๐ŸŒŽ

  • Protect Sensitive Logic: Prevent unauthorized access to your code.

  • Simple Deployment: No complicated setup or runtime requirements.

  • Peace of Mind: Focus on your work without worrying about code theft.

Get Started Now ๐Ÿƒโ€โ™‚๏ธ

  1. Visit GateCode.

  2. Upload your Python script.

  3. Download your encrypted package and deploy it securely.

๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 39000296 โ€บ how-to-send-the-encrypted-data-to-the-client
python - How to send the encrypted data to the client? - Stack Overflow
April 26, 2017 - Sign up to request clarification or add additional context in comments. ... It is rather difficult to check your code without seeing the encryption module referenced in your code. With such functionality absent, testing to find out where the problem is becomes impossible. As such, the following programs are provided along with the implementation of another encryption module. The server should be run from the command line and requires a port number and password to be supplied upon execution.