nkeys (Python)

0.2.1 · active · verified Thu Apr 16

The `nkeys` Python library, currently at version 0.2.1, provides a public-key signature system built upon Ed25519 cryptography, specifically designed for identity, authentication, and authorization within the NATS ecosystem. It offers utilities for generating, encoding, and managing NATS-compatible key pairs (Operators, Accounts, Users, Servers, Clusters). The library maintains a low-to-moderate release cadence, with recent updates focusing on dependency management and Python version compatibility.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to generate a new NATS user key pair (seed, public, and private keys) using `nkeys` and `pynacl`, then sign and verify a message. It also highlights the importance of wiping sensitive key data.

import nkeys
from nacl.signing import SigningKey
import os

# 1. Generate a raw Ed25519 signing key using PyNaCl
raw_signing_key = SigningKey.generate()

# 2. Encode the raw key as a NATS user seed (e.g., SU...)
# The `encode_seed` function combines the raw private key with the NATS prefix.
# Use nkeys.PREFIX_BYTE_USER for a user key, nkeys.PREFIX_BYTE_ACCOUNT for an account, etc.
user_seed_bytes = nkeys.encode_seed(nkeys.PREFIX_BYTE_USER, raw_signing_key.encode())

print(f"Generated User Seed (NKEY format): {user_seed_bytes.decode()}")

# 3. Create an NKEYS KeyPair object from the seed
key_pair = nkeys.from_seed(user_seed_bytes)

print(f"Public Key (U...): {key_pair.public_key.decode()}")
# The private key and seed should be kept secret.
# The raw private key is a 64-byte Ed25519 private key.
print(f"Private Key (raw hex - keep secret!): {key_pair.private_key.hex()}")
print(f"Seed (S... NKEY format - keep secret!): {key_pair.seed.decode()}")

# 4. Example of signing data
data_to_sign = b"Hello NATS! This is a test message."
signature = key_pair.sign(data_to_sign)
print(f"Signature for data: {signature.hex()}")

# 5. Verification (a KeyPair created from the public key can verify signatures)
verifier_key_pair = nkeys.from_public_key(key_pair.public_key)
try:
    verifier_key_pair.verify(data_to_sign, signature)
    print("Signature verified successfully.")
except Exception as e:
    print(f"Signature verification failed: {e}")

# 6. Secure handling: wipe sensitive key material from memory when no longer needed
key_pair.wipe()
print("Sensitive key material wiped from memory for security.")

view raw JSON →