Post-Quantum Secure Messaging System into a real-time encrypted chat client/server using Python Programming

Post-Quantum Secure Messaging System into a real-time encrypted chat client/server using Python Programming

#PostQuantumSecurity #QuantumResistant #PQEncryption #EncryptedMessaging

#SecureChat #RealTimeEncryption #PythonSecurity #Cybersecurity #EndToEndEncryption

#SecureMessaging

Brief Idea on Post-Quantum Cryptography (PQC)

Post-Quantum Cryptography refers to cryptographic algorithms that are designed to be secure against the potential threat of quantum computers. Quantum computers could efficiently break many widely-used cryptographic systems (like RSA, ECC, and DH) using algorithms such as Shor’s algorithm. PQC algorithms are based on mathematical problems that remain hard even for quantum computers — like lattice-based, code-based, multivariate, and hash-based cryptography.

The U.S. National Institute of Standards and Technology (NIST) is currently leading the effort to standardize PQC. Some of the most prominent algorithms include:

  • Kyber (for key encapsulation)
  • Dilithium (for digital signatures)
  • Falcon, SPHINCS+, etc.


Hands-On: PQC with Python + AI Integration

Let’s implement a basic Kyber key encapsulation using Python and AI to automatically select secure parameters based on the use-case (e.g., high-speed vs high-security).


Step 1: Setup with py-pqclean

Install PQClean (a collection of clean implementations of PQC algorithms):

pip install pqclean


Step 2: Implement Key Generation and Encryption (Kyber Example)

from pqclean import Kyber512

import random

 

# Step 1: Key generation

pk, sk = Kyber512.keypair()

 

# Step 2: Encapsulation (for sender)

ciphertext, shared_secret_sender = Kyber512.encapsulate(pk)

 

# Step 3: Decapsulation (for receiver)

shared_secret_receiver = Kyber512.decapsulate(ciphertext, sk)

 

print("Shared secret matches:", shared_secret_sender == shared_secret_receiver)


Step 3: Integrate AI (Optional)

Use a simple AI model (e.g., decision tree or rules-based logic) to choose the right algorithm:

def choose_algorithm(speed_priority=True, memory_constrained=False):

    if speed_priority:

        return "Kyber512"

    elif memory_constrained:

        return "Kyber768"

    else:

        return "Kyber1024"

 

# Example:

algo = choose_algorithm(speed_priority=True)

print(f"Selected PQC algorithm: {algo}")


Use Case for AI:

In a real-world application, you can train an ML model to:

  • Recommend parameters based on latency and bandwidth.
  • Monitor runtime performance to adapt key size.
  • Detect threats and switch algorithms dynamically.

AI-Powered PQC Recommendation System (with Python)

import pandas as pd        
from sklearn.tree import DecisionTreeClassifier        
         
# Sample training data        
data = {        
    "security_level": ["low", "medium", "high", "high", "medium", "low"],        
    "device_constraints": ["low_memory", "standard", "standard", "low_memory", "low_memory", "standard"],        
    "use_case": ["real_time", "general", "storage", "real_time", "storage", "general"],        
    "recommended_algo": ["Kyber512", "Kyber768", "Kyber1024", "Kyber768", "Kyber768", "Kyber512"]        
}        
         
df = pd.DataFrame(data)        
         
# One-hot encoding for categorical variables        
df_encoded = pd.get_dummies(df.drop("recommended_algo", axis=1))        
target = df["recommended_algo"]        
         
# Train the decision tree classifier        
model = DecisionTreeClassifier()        
model.fit(df_encoded, target)        
         
# AI-based recommendation function        
def recommend_algorithm(security_level, device_constraints, use_case):        
    input_data = pd.DataFrame([{        
        "security_level_" + security_level: 1,        
        "device_constraints_" + device_constraints: 1,        
        "use_case_" + use_case: 1        
    }])        
         
    for col in df_encoded.columns:        
        if col not in input_data.columns:        
            input_data[col] = 0        
         
    input_data = input_data[df_encoded.columns]        
    return model.predict(input_data)[0]        
         
# Example usage        
print(recommend_algorithm("high", "standard", "storage"))  # Output: Kyber1024        

We can integrate the AI-powered PQC recommendation system into a simple secure messaging application using pqcrypto. We'll use the recommendation to select the best Kyber variant and encrypt messages accordingly.


 Secure Messaging App with AI + PQC (Python Implementation)

Requirements

Install these packages:

pip install pqcrypto pandas scikit-learn        

 Step 1: AI Recommendation System

(Same as before — embedded into the application logic)

import pandas as pd        
from sklearn.tree import DecisionTreeClassifier        
         
# Train AI Model        
data = {        
    "security_level": ["low", "medium", "high", "high", "medium", "low"],        
    "device_constraints": ["low_memory", "standard", "standard", "low_memory", "low_memory", "standard"],        
    "use_case": ["real_time", "general", "storage", "real_time", "storage", "general"],        
    "recommended_algo": ["kyber512", "kyber768", "kyber1024", "kyber768", "kyber768", "kyber512"]        
}        
         
df = pd.DataFrame(data)        
df_encoded = pd.get_dummies(df.drop("recommended_algo", axis=1))        
target = df["recommended_algo"]        
         
model = DecisionTreeClassifier()        
model.fit(df_encoded, target)        
         
def recommend_algorithm(security_level, device_constraints, use_case):        
    input_data = pd.DataFrame([{        
        f"security_level_{security_level}": 1,        
        f"device_constraints_{device_constraints}": 1,        
        f"use_case_{use_case}": 1        
    }])        
    for col in df_encoded.columns:        
        if col not in input_data.columns:        
            input_data[col] = 0        
    input_data = input_data[df_encoded.columns]        
    return model.predict(input_data)[0]        

 Step 2: Secure Messaging with pqcrypto

from pqcrypto.kem import kyber512, kyber768, kyber1024        
         
# Map algorithm name to module        
algorithm_map = {        
    "kyber512": kyber512,        
    "kyber768": kyber768,        
    "kyber1024": kyber1024        
}        
         
# User-defined profile        
security_level = "high"        
device_constraints = "standard"        
use_case = "storage"        
         
# AI recommends best algorithm        
recommended = recommend_algorithm(security_level, device_constraints, use_case)        
print(f"[AI] Recommended PQC algorithm: {recommended}")        
         
# Get the PQC module        
algo = algorithm_map[recommended]        
         
# Keypair generation        
pk, sk = algo.generate_keypair()        
         
# Simulate sender encrypting a shared secret        
ciphertext, shared_secret_sender = algo.encrypt(pk)        
         
# Simulate receiver decrypting to get the shared secret        
shared_secret_receiver = algo.decrypt(ciphertext, sk)        
         
# Check secret match        
assert shared_secret_sender == shared_secret_receiver        
         
print("[Secure Messaging] Shared secret established successfully.")        
         
# Now simulate encrypting a simple message using the shared secret        
from Crypto.Cipher import AES        
from Crypto.Util.Padding import pad, unpad        
import hashlib        
import os        
         
# Derive AES key from PQC shared secret        
key = hashlib.sha256(shared_secret_sender).digest()        
         
# Encrypt a message        
def encrypt_message(message, key):        
    iv = os.urandom(16)        
    cipher = AES.new(key, AES.MODE_CBC, iv)        
    ciphertext = cipher.encrypt(pad(message.encode(), AES.block_size))        
    return iv + ciphertext        
         
# Decrypt a message        
def decrypt_message(ciphertext, key):        
    iv = ciphertext[:16]        
    cipher = AES.new(key, AES.MODE_CBC, iv)        
    decrypted = unpad(cipher.decrypt(ciphertext[16:]), AES.block_size)        
    return decrypted.decode()        
         
# Test it        
message = "Hello from a post-quantum secure world!"        
encrypted = encrypt_message(message, key)        
decrypted = decrypt_message(encrypted, key)        
         
print("[Encrypted] ->", encrypted.hex())        
print("[Decrypted] ->", decrypted)        

Output

 [AI] Recommended PQC algorithm: kyber1024        
[Secure Messaging] Shared secret established successfully.        
[Encrypted] -> 4e7392df13... (hex)        
[Decrypted] -> Hello from a post-quantum secure world!        

Action happening here -

1.      AI recommends the best post-quantum algorithm (Kyber variant).

2.      Kyber key exchange establishes a shared secret.

3.      AES encryption (from PyCryptodome) is used for message confidentiality.

4.      Result: A hybrid secure messaging system resistant to quantum attacks.


Post-Quantum Secure Messaging System into a real-time encrypted chat client/server using:

·         AI-Powered Kyber algorithm selection

·         pqcrypto for post-quantum key exchange

·          PyCryptodome for symmetric encryption (AES-CBC)

·         socket library for networking


 Option 1: Post-Quantum Secure Chat (Client/Server)

We’ll build two Python scripts:

·         server.py – Handles key exchange + receives/decrypts messages

·         client.py – Connects to server + sends encrypted messages


Shared Library: pqc_utils.py

Save this first to a file called pqc_utils.py:

import hashlib        
import os        
from pqcrypto.kem import kyber512, kyber768, kyber1024        
from Crypto.Cipher import AES        
from Crypto.Util.Padding import pad, unpad        
import pandas as pd        
from sklearn.tree import DecisionTreeClassifier        
         
# AI recommendation system        
def train_model():        
    data = {        
        "security_level": ["low", "medium", "high", "high", "medium", "low"],        
        "device_constraints": ["low_memory", "standard", "standard", "low_memory", "low_memory", "standard"],        
        "use_case": ["real_time", "general", "storage", "real_time", "storage", "general"],        
        "recommended_algo": ["kyber512", "kyber768", "kyber1024", "kyber768", "kyber768", "kyber512"]        
    }        
    df = pd.DataFrame(data)        
    df_encoded = pd.get_dummies(df.drop("recommended_algo", axis=1))        
    model = DecisionTreeClassifier()        
    model.fit(df_encoded, df["recommended_algo"])        
    return model, df_encoded.columns        
         
model, model_cols = train_model()        
         
def recommend_algorithm(security_level, device_constraints, use_case):        
    input_data = pd.DataFrame([{        
        f"security_level_{security_level}": 1,        
        f"device_constraints_{device_constraints}": 1,        
        f"use_case_{use_case}": 1        
    }])        
    for col in model_cols:        
        if col not in input_data.columns:        
            input_data[col] = 0        
    input_data = input_data[model_cols]        
    return model.predict(input_data)[0]        
         
algorithm_map = {        
    "kyber512": kyber512,        
    "kyber768": kyber768,        
    "kyber1024": kyber1024        
}        
         
def derive_aes_key(shared_secret):        
    return hashlib.sha256(shared_secret).digest()        
         
def encrypt_message(msg, key):        
    iv = os.urandom(16)        
    cipher = AES.new(key, AES.MODE_CBC, iv)        
    return iv + cipher.encrypt(pad(msg.encode(), AES.block_size))        
         
def decrypt_message(ciphertext, key):        
    iv = ciphertext[:16]        
    cipher = AES.new(key, AES.MODE_CBC, iv)        
    return unpad(cipher.decrypt(ciphertext[16:]), AES.block_size).decode()        

 server.py

import socket        
from pqc_utils import *        
         
# Recommend PQC algorithm        
algo_name = recommend_algorithm("high", "standard", "real_time")        
algo = algorithm_map[algo_name]        
print(f"[Server] Using: {algo_name}")        
         
# Generate server keypair        
pk, sk = algo.generate_keypair()        
         
# Start server        
server = socket.socket()        
server.bind(("localhost", 9999))        
server.listen(1)        
print("[Server] Waiting for connection...")        
         
conn, addr = server.accept()        
print("[Server] Connected to", addr)        
         
# Send public key to client        
conn.send(pk)        
         
# Receive ciphertext from client        
ciphertext = conn.recv(2048)        
shared_secret = algo.decrypt(ciphertext, sk)        
aes_key = derive_aes_key(shared_secret)        
         
# Communication loop        
while True:        
    encrypted_msg = conn.recv(4096)        
    if not encrypted_msg:        
        break        
    msg = decrypt_message(encrypted_msg, aes_key)        
    print(f"[Client]: {msg}")        

 client.py

import socket        
from pqc_utils import *        
         
# Recommend PQC algorithm        
algo_name = recommend_algorithm("high", "standard", "real_time")        
algo = algorithm_map[algo_name]        
print(f"[Client] Using: {algo_name}")        
         
# Connect to server        
client = socket.socket()        
client.connect(("localhost", 9999))        
         
# Receive server public key        
pk = client.recv(1024)        
         
# Encrypt shared secret with server's public key        
ciphertext, shared_secret = algo.encrypt(pk)        
client.send(ciphertext)        
         
aes_key = derive_aes_key(shared_secret)        
         
# Send encrypted messages        
try:        
    while True:        
        msg = input("You: ")        
        if msg.lower() == "exit":        
            break        
        encrypted = encrypt_message(msg, aes_key)        
        client.send(encrypted)        
except KeyboardInterrupt:        
    pass        
finally:        
    client.close()        

 How to Run Instructions

1.      Run server.py first in one terminal

2.      Run client.py in another terminal

3.      Start typing encrypted messages!


Security Features

·         AI-powered selection of post-quantum secure Kyber variant

·         Encrypted symmetric channel using AES-256-CBC

·         Secure key exchange over Kyber (quantum-resistant)

·         Real-time communication with sockets

 

 

To view or add a comment, sign in

More articles by Nishanta Ranjan Nanda

Explore content categories