>NoiseFramework

NoiseFramework Examples

Real-world examples of using NoiseFramework in Python applications

Browse by Category

Basic Examples
Simple handshakes and basic usage patterns
Client-Server
Building secure client-server applications
File Encryption
Encrypting and decrypting files securely
Chat Applications
Real-time encrypted messaging systems
Advanced Patterns
Complex handshake patterns and use cases
Integration Examples
WebSocket, async/await, and more

Featured Examples

Basic Client-Server
Simple client-server example with mutual authentication using XX pattern
BeginnerNoise_XX
import socket
from noiseframework import NoiseHandshake, NoiseTransport

# Server configuration
HOST = '127.0.0.1'
PORT = 5000

# Create server socket
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as server:
    server.bind((HOST, PORT))
    server.listen(1)
    print(f"Server listening on {HOST}:{PORT}")
    
    # Accept connection
    conn, addr = server.accept()
    with conn:
        print(f"Connected by {addr}")
        
        # Setup Noise handshake
        responder = NoiseHandshake("Noise_XX_25519_ChaChaPoly_SHA256")
        responder.set_as_responder()
        responder.generate_static_keypair()
        responder.initialize()
        
        # Perform handshake
        msg1 = conn.recv(1024)
        responder.read_message(msg1)
        
        msg2 = responder.write_message(b"")
        conn.send(msg2)
        
        msg3 = conn.recv(1024)
        responder.read_message(msg3)
        
        # Create transport
        send_cipher, recv_cipher = responder.to_transport()
        transport = NoiseTransport(send_cipher, recv_cipher)
        
        # Receive encrypted message
        ciphertext = conn.recv(1024)
        plaintext = transport.receive(ciphertext)
        print(f"Received: {plaintext.decode()}")
        
        # Send encrypted response
        response = transport.send(b"Hello from server!")
        conn.send(response)

What This Example Shows

  • • Complete XX handshake between client and server
  • • Socket-based communication with TCP
  • • Post-handshake encrypted messaging with NoiseTransport
  • • Mutual authentication with static keypairs
File Encryption
Encrypt and decrypt files using Noise transport with anonymous pattern
BeginnerNoise_NN
from noiseframework import NoiseHandshake, NoiseTransport
from pathlib import Path

def encrypt_file(input_path: str, output_path: str):
    """Encrypt a file using Noise NN pattern"""
    # Setup handshake (NN pattern - no authentication)
    initiator = NoiseHandshake("Noise_NN_25519_ChaChaPoly_SHA256")
    initiator.set_as_initiator()
    initiator.initialize()
    
    responder = NoiseHandshake("Noise_NN_25519_ChaChaPoly_SHA256")
    responder.set_as_responder()
    responder.initialize()
    
    # Perform handshake
    msg1 = initiator.write_message(b"")
    responder.read_message(msg1)
    msg2 = responder.write_message(b"")
    initiator.read_message(msg2)
    
    # Create transport
    send_cipher, recv_cipher = initiator.to_transport()
    transport = NoiseTransport(send_cipher, recv_cipher)
    
    # Read and encrypt file
    plaintext = Path(input_path).read_bytes()
    ciphertext = transport.send(plaintext)
    
    # Save handshake data + ciphertext
    handshake_hash = initiator.get_handshake_hash()
    Path(output_path).write_bytes(handshake_hash + ciphertext)
    print(f"Encrypted {input_path} -> {output_path}")

def decrypt_file(input_path: str, output_path: str):
    """Decrypt a file encrypted with Noise"""
    # Read encrypted data
    data = Path(input_path).read_bytes()
    handshake_hash = data[:32]
    ciphertext = data[32:]
    
    # Recreate handshake
    responder = NoiseHandshake("Noise_NN_25519_ChaChaPoly_SHA256")
    responder.set_as_responder()
    responder.initialize()
    # ... perform handshake ...
    
    send_cipher, recv_cipher = responder.to_transport()
    transport = NoiseTransport(recv_cipher, send_cipher)
    
    # Decrypt and save
    plaintext = transport.receive(ciphertext)
    Path(output_path).write_bytes(plaintext)
    print(f"Decrypted {input_path} -> {output_path}")

# Usage
encrypt_file("document.pdf", "document.pdf.encrypted")
decrypt_file("document.pdf.encrypted", "document_decrypted.pdf")

What This Example Shows

  • • File encryption using Noise NN pattern (no authentication)
  • • Saving handshake hash for verification
  • • Encrypting/decrypting arbitrary binary data
  • • Working with the filesystem using pathlib
Simple Chat Application
Two-party encrypted chat with real-time message encryption
IntermediateNoise_XX
import socket
import threading
from noiseframework import NoiseHandshake, NoiseTransport

class SecureChat:
    def __init__(self, is_initiator: bool):
        self.transport = None
        self.is_initiator = is_initiator
    
    def setup_connection(self, sock):
        """Perform Noise handshake"""
        hs = NoiseHandshake("Noise_XX_25519_ChaChaPoly_SHA256")
        if self.is_initiator:
            hs.set_as_initiator()
        else:
            hs.set_as_responder()
        
        hs.generate_static_keypair()
        hs.initialize()
        
        # Perform handshake...
        # (handshake code omitted for brevity)
        
        send_cipher, recv_cipher = hs.to_transport()
        self.transport = NoiseTransport(send_cipher, recv_cipher)
    
    def send_message(self, sock, message: str):
        """Encrypt and send a message"""
        ciphertext = self.transport.send(message.encode('utf-8'))
        sock.sendall(ciphertext)
    
    def receive_message(self, sock) -> str:
        """Receive and decrypt a message"""
        ciphertext = sock.recv(4096)
        plaintext = self.transport.receive(ciphertext)
        return plaintext.decode('utf-8')
    
    def chat_loop(self, sock):
        """Main chat loop"""
        def receive_loop():
            while True:
                try:
                    msg = self.receive_message(sock)
                    print(f"\\nPeer: {msg}")
                except Exception:
                    break
        
        # Start receive thread
        thread = threading.Thread(target=receive_loop)
        thread.start()
        
        # Send loop
        while True:
            msg = input("You: ")
            self.send_message(sock, msg)

# Usage example
chat = SecureChat(is_initiator=True)
# ... setup socket connection ...
chat.setup_connection(sock)
chat.chat_loop(sock)

What This Example Shows

  • • Real-time encrypted chat with threading
  • • Bidirectional encrypted communication
  • • Object-oriented design with NoiseFramework
  • • Message encoding/decoding with UTF-8

More Examples

WebSocket Integration
Using NoiseFramework with WebSocket connections
Advanced
Async/Await Pattern
Using NoiseFramework with asyncio for async operations
Advanced
Pre-Shared Keys (IK)
Using IK pattern with pre-shared public keys
Intermediate
Ready to Build?
Check out these resources to continue learning