Noise Protocol Framework Implementation

0.3.1 · active · verified Thu Apr 16

The `noiseprotocol` library provides a Python implementation of the Noise Protocol Framework (Revision 5), a widely used framework for building secure cryptographic protocols. It focuses on offering a robust and flexible API for performing handshakes and secure transport of data, supporting various handshake patterns and cipher suites. The current version is 0.3.1, and releases are infrequent, reflecting the stability of the underlying protocol.

Common errors

Warnings

Install

Imports

Quickstart

This example demonstrates a basic Noise Protocol handshake using the IK pattern, followed by secure transport of a message. It sets up an initiator and a responder, performs the handshake by exchanging messages, and then uses the resulting transport states to encrypt and decrypt a payload.

import secrets
from noiseprotocol.constants import HandshakePattern, CipherSuite, NoiseConnectionRole
from noiseprotocol.handshake import HandshakeState, Keypair

# 1. Define static keys (can be pre-shared or generated once)
initiator_static_key = Keypair(private=secrets.token_bytes(32))
responder_static_key = Keypair(private=secrets.token_bytes(32))

# 2. Setup Initiator
initiator_hs = HandshakeState(
    role=NoiseConnectionRole.INITIATOR,
    pattern=HandshakePattern.IK,
    static_key=initiator_static_key,
    remote_static_key=responder_static_key.public, # Initiator knows Responder's public key
    cipher_suite=CipherSuite.AESGCM256_SHA256_X25519
)
initiator_hs.initialize()

# 3. Setup Responder
responder_hs = HandshakeState(
    role=NoiseConnectionRole.RESPONDER,
    pattern=HandshakePattern.IK,
    static_key=responder_static_key,
    cipher_suite=CipherSuite.AESGCM256_SHA256_X25519
)
responder_hs.initialize()

# 4. Perform Handshake (simplified for example, messages would be sent over network)
# Initiator sends first message
message_initiator_to_responder, _ = initiator_hs.write_message(b"")

# Responder receives message
_, post_handshake_state_responder = responder_hs.read_message(message_initiator_to_responder)

# Responder sends second message
message_responder_to_initiator, _ = responder_hs.write_message(b"")

# Initiator receives message
_, post_handshake_state_initiator = initiator_hs.read_message(message_responder_to_initiator)

# Handshake complete, now use post_handshake_state for transport
if post_handshake_state_initiator and post_handshake_state_responder:
    plaintext = b"Hello, secure world!"
    ciphertext = post_handshake_state_initiator.write_message(plaintext)
    decrypted = post_handshake_state_responder.read_message(ciphertext)

    assert plaintext == decrypted
    print("Handshake and transport successful!")
else:
    print("Handshake failed.")

view raw JSON →