diff --git a/EXPORTABLE_DESIGN.md b/EXPORTABLE_DESIGN.md deleted file mode 100644 index 8aff61af..00000000 --- a/EXPORTABLE_DESIGN.md +++ /dev/null @@ -1,309 +0,0 @@ -# Exportable C NOSTR Library Design Guide - -This document outlines the design principles and structure for making the C NOSTR library easily exportable and reusable across multiple projects. - -## Overview - -The C NOSTR library is designed as a modular, self-contained implementation that can be easily integrated into other projects while maintaining compatibility with the broader NOSTR ecosystem. - -## Design Principles - -### 1. Modular Architecture -- **Core Layer**: Essential NOSTR functionality (`nostr_core.c/h`) -- **Crypto Layer**: Self-contained cryptographic primitives (`nostr_crypto.c/h`) -- **WebSocket Layer**: Optional networking functionality (`nostr_websocket/`) -- **Dependencies**: Minimal external dependencies (only cJSON and mbedTLS) - -### 2. Clean API Surface -- Consistent function naming with `nostr_` prefix -- Clear return codes using `NOSTR_SUCCESS`/`NOSTR_ERROR_*` constants -- Well-documented function signatures -- No global state where possible - -### 3. Self-Contained Crypto -- Custom implementations of SHA-256, HMAC, secp256k1 -- BIP39 wordlist embedded in code -- No external crypto library dependencies for core functionality -- Optional mbedTLS integration for enhanced security - -### 4. Cross-Platform Compatibility -- Standard C99 code -- Platform-specific code isolated in separate modules -- ARM64 and x86_64 tested builds -- Static library compilation support - -## Library Structure - -``` -c_nostr/ -├── nostr_core.h # High-level API -├── nostr_core.c # Implementation -├── nostr_crypto.h # Crypto primitives API -├── nostr_crypto.c # Self-contained crypto -├── libnostr_core.a # Static library (x86_64) -├── libnostr_core.so # Shared library (x86_64) -├── cjson/ # JSON parsing (vendored) -├── mbedtls/ # Optional crypto backend -├── examples/ # Usage examples -├── tests/ # Test suites -└── nostr_websocket/ # Optional WebSocket layer -``` - -## Integration Methods - -### Method 1: Static Library Linking - -**Best for**: Applications that want a single binary with all NOSTR functionality embedded. - -```bash -# Build the library -make lib - -# In your project Makefile: -CFLAGS += -I/path/to/c_nostr -LDFLAGS += -L/path/to/c_nostr -lnostr_core -lm -static -``` - -**Usage:** -```c -#include "nostr_core.h" - -int main() { - if (nostr_init() != NOSTR_SUCCESS) { - return 1; - } - - unsigned char private_key[32], public_key[32]; - nostr_generate_keypair(private_key, public_key); - - cJSON* event = nostr_create_text_event("Hello NOSTR!", private_key); - // ... use event - - nostr_cleanup(); - return 0; -} -``` - -### Method 2: Source Code Integration - -**Best for**: Applications that want to customize the crypto backend or minimize dependencies. - -```bash -# Copy essential files to your project: -cp nostr_core.{c,h} your_project/src/ -cp nostr_crypto.{c,h} your_project/src/ -cp -r cjson/ your_project/src/ -``` - -**Compile with your project:** -```c -// In your source -#include "nostr_core.h" -// Use NOSTR functions directly -``` - -### Method 3: Git Submodule - -**Best for**: Projects that want to track upstream changes and contribute back. - -```bash -# In your project root: -git submodule add https://github.com/yourorg/c_nostr.git deps/c_nostr -git submodule update --init --recursive - -# In your Makefile: -CFLAGS += -Ideps/c_nostr -LDFLAGS += -Ldeps/c_nostr -lnostr_core -``` - -### Method 4: Shared Library - -**Best for**: System-wide installation or multiple applications sharing the same NOSTR implementation. - -```bash -# Install system-wide -sudo make install - -# In your project: -CFLAGS += $(pkg-config --cflags nostr_core) -LDFLAGS += $(pkg-config --libs nostr_core) -``` - -## API Design for Exportability - -### Consistent Error Handling -```c -typedef enum { - NOSTR_SUCCESS = 0, - NOSTR_ERROR_INVALID_INPUT = -1, - NOSTR_ERROR_CRYPTO_FAILED = -2, - NOSTR_ERROR_MEMORY_ALLOCATION = -3, - NOSTR_ERROR_JSON_PARSE = -4, - NOSTR_ERROR_NETWORK = -5 -} nostr_error_t; - -const char* nostr_strerror(int error_code); -``` - -### Clean Resource Management -```c -// Always provide cleanup functions -int nostr_init(void); -void nostr_cleanup(void); - -// JSON objects returned should be freed by caller -cJSON* nostr_create_text_event(const char* content, const unsigned char* private_key); -// Caller must call cJSON_Delete(event) when done -``` - -### Optional Features -```c -// Compile-time feature toggles -#ifndef NOSTR_DISABLE_WEBSOCKETS -int nostr_connect_relay(const char* url); -#endif - -#ifndef NOSTR_DISABLE_IDENTITY_PERSISTENCE -int nostr_save_identity(const unsigned char* private_key, const char* password, int account); -#endif -``` - -## Configuration System - -### Build-Time Configuration -```c -// nostr_config.h (generated during build) -#define NOSTR_VERSION "1.0.0" -#define NOSTR_HAS_MBEDTLS 1 -#define NOSTR_HAS_WEBSOCKETS 1 -#define NOSTR_STATIC_BUILD 1 -``` - -### Runtime Configuration -```c -typedef struct { - int log_level; - char* identity_file_path; - int default_account; - int enable_networking; -} nostr_config_t; - -int nostr_set_config(const nostr_config_t* config); -const nostr_config_t* nostr_get_config(void); -``` - -## Testing and Validation - -### Ecosystem Compatibility Testing -The library includes comprehensive test suites that validate compatibility with reference implementations like `nak`: - -```bash -# Run all tests -cd tests && make test - -# Test specific functionality -make test-crypto # Cryptographic primitives -make test-core # High-level NOSTR functions -``` - -### Test Vectors -Real-world test vectors are generated using `nak` to ensure ecosystem compatibility: -- Key generation and derivation (BIP39/BIP32) -- Event creation and signing -- Bech32 encoding/decoding -- Message serialization - -## Documentation for Exporters - -### Essential Files Checklist -For projects integrating this library, you need: - -**Core Files (Required):** -- `nostr_core.h` - Main API -- `nostr_core.c` - Implementation -- `nostr_crypto.h` - Crypto API -- `nostr_crypto.c` - Self-contained crypto -- `cjson/` directory - JSON parsing - -**Optional Files:** -- `nostr_websocket/` - WebSocket relay support -- `mbedtls/` - Enhanced crypto backend -- `examples/` - Usage examples -- `tests/` - Validation tests - -### Minimal Integration Example -```c -// minimal_nostr.c - Smallest possible integration -#include "nostr_core.h" - -int main() { - // Initialize library - nostr_init(); - - // Generate keypair - unsigned char priv[32], pub[32]; - nostr_generate_keypair(priv, pub); - - // Create and sign event - cJSON* event = nostr_create_text_event("Hello from my app!", priv); - char* json_string = cJSON_Print(event); - printf("Event: %s\n", json_string); - - // Cleanup - free(json_string); - cJSON_Delete(event); - nostr_cleanup(); - return 0; -} -``` - -**Compile:** -```bash -gcc -I. minimal_nostr.c nostr_core.c nostr_crypto.c cjson/cJSON.c -lm -o minimal_nostr -``` - -## Future Considerations - -### Language Bindings -The C library is designed to be easily wrapped: -- **Python**: Use ctypes or cffi -- **JavaScript**: Use Node.js FFI or WASM compilation -- **Go**: Use cgo -- **Rust**: Use bindgen for FFI bindings - -### WebAssembly Support -The library can be compiled to WebAssembly for browser usage: -```bash -emcc -O3 -s WASM=1 -s EXPORTED_FUNCTIONS='["_nostr_init", "_nostr_generate_keypair"]' \ - nostr_core.c nostr_crypto.c cjson/cJSON.c -o nostr.wasm -``` - -### Package Manager Support -Future versions may include: -- pkgconfig files for system installation -- CMake integration for easier builds -- vcpkg/Conan package definitions - -## Contributing Back - -Projects using this library are encouraged to: -1. Report compatibility issues -2. Submit test vectors from their use cases -3. Contribute performance improvements -4. Add support for additional NIPs - -## Version Compatibility - -The library follows semantic versioning: -- **Major**: Breaking API changes -- **Minor**: New features, backward compatible -- **Patch**: Bug fixes - -API stability guarantees: -- All functions prefixed with `nostr_` are part of the stable API -- Internal functions (static or prefixed with `_`) may change -- Configuration structures may be extended but not modified - ---- - -This design ensures the C NOSTR library can be easily adopted by other projects while maintaining high compatibility with the NOSTR ecosystem standards. diff --git a/EXPORT_GUIDE.md b/EXPORT_GUIDE.md deleted file mode 100644 index 40d39bea..00000000 --- a/EXPORT_GUIDE.md +++ /dev/null @@ -1,29 +0,0 @@ -# c-nostr Export and Implementation Guide - -## Overview - -This guide provides essential information for developers using the `c-nostr` library, particularly regarding the capabilities and limitations of its self-contained modules, such as the HTTP client. - -## HTTP Client (`http_client.c`) - -The `http_client` module is a lightweight, self-contained HTTP/HTTPS client designed for simple and direct web requests. It is ideal for tasks like fetching NIP-11 information from Nostr relays or interacting with standard, permissive web APIs. - -### Key Features - -* **Self-Contained**: It is built with `mbedTLS` and has no external dependencies beyond standard C libraries, making it highly portable. -* **Simplicity**: It provides a straightforward `http_get()` function for making web requests. -* **TLS Support**: It supports HTTPS and basic TLS 1.3/1.2 features, including SNI (Server Name Indication) and ALPN (Application-Layer Protocol Negotiation). - -### Limitations - -The `http_client` is intentionally simple and is **not a full-featured web browser**. Due to its minimalist design, it will likely be blocked by websites that employ advanced anti-bot protection systems. - -* **Incompatibility with Advanced Bot Protection**: Sites like Google, Cloudflare, and others use sophisticated fingerprinting techniques to distinguish between real browsers and automated clients. They analyze the exact combination of TLS cipher suites, TLS extensions, and HTTP headers. Our client's fingerprint does not match a standard browser, so these sites will preemptively drop the connection, typically resulting in a `HTTP_ERROR_NETWORK` error. - -* **Intended Use Case**: This client is best suited for interacting with known, friendly APIs and Nostr relays. It is **not** designed for general web scraping or for accessing services that are heavily guarded against automated traffic. - -### Best Practices - -* **Use for APIs and Relays**: Rely on this client for fetching data from well-defined, public endpoints that do not have aggressive bot-detection measures in place. -* **Avoid Protected Sites**: Do not attempt to use this client to access services like Google Search, as such attempts will fail. For those use cases, a full-featured library like `libcurl` or a dedicated web-scraping framework is required. -* **Check the Test Suite**: The `tests/http_client_test.c` file contains test cases that demonstrate both the successful use cases (e.g., `httpbin.org`) and the expected failures (e.g., `google.com`), providing a clear reference for the client's capabilities. diff --git a/GENERIC_AUTOMATIC_VERSIONING_GUIDE.md b/GENERIC_AUTOMATIC_VERSIONING_GUIDE.md deleted file mode 100644 index c8fcc0a6..00000000 --- a/GENERIC_AUTOMATIC_VERSIONING_GUIDE.md +++ /dev/null @@ -1,361 +0,0 @@ -# Generic Automatic Version Increment System for Any Repository - -Here's a generalized implementation guide for adding automatic versioning to any project: - -## Core Concept -**Automatic patch version increment with each build** - Every build automatically increments the patch version: v0.1.0 → v0.1.1 → v0.1.2, etc. - -## Implementation Steps - -### 1. Add Version Increment Function to Build Script -Add this function to your build script (bash example): - -```bash -# Function to automatically increment version -increment_version() { - echo "[INFO] Incrementing version..." - - # Check if we're in a git repository - if ! git rev-parse --git-dir > /dev/null 2>&1; then - echo "[WARNING] Not in a git repository - skipping version increment" - return 0 - fi - - # Get the highest version tag (not chronologically latest) - LATEST_TAG=$(git tag -l 'v*.*.*' | sort -V | tail -n 1 || echo "v0.1.0") - if [[ -z "$LATEST_TAG" ]]; then - LATEST_TAG="v0.1.0" - fi - - # Extract version components (remove 'v' prefix) - VERSION=${LATEST_TAG#v} - - # Parse major.minor.patch using regex - if [[ $VERSION =~ ^([0-9]+)\.([0-9]+)\.([0-9]+)$ ]]; then - MAJOR=${BASH_REMATCH[1]} - MINOR=${BASH_REMATCH[2]} - PATCH=${BASH_REMATCH[3]} - else - echo "[ERROR] Invalid version format in tag: $LATEST_TAG" - echo "[ERROR] Expected format: v0.1.0" - return 1 - fi - - # Increment patch version - NEW_PATCH=$((PATCH + 1)) - NEW_VERSION="v${MAJOR}.${MINOR}.${NEW_PATCH}" - - echo "[INFO] Current version: $LATEST_TAG" - echo "[INFO] New version: $NEW_VERSION" - - # Create new git tag - if git tag "$NEW_VERSION" 2>/dev/null; then - echo "[SUCCESS] Created new version tag: $NEW_VERSION" - else - echo "[WARNING] Tag $NEW_VERSION already exists - using existing version" - NEW_VERSION=$LATEST_TAG - fi - - # Update VERSION file for compatibility - echo "${NEW_VERSION#v}" > VERSION - echo "[SUCCESS] Updated VERSION file to ${NEW_VERSION#v}" -} -``` - -### 2. Generate Version Header Files (For C/C++ Projects) -Add this to the increment_version function: - -```bash -# Generate version.h header file (adjust path as needed) -cat > src/version.h << EOF -/* - * Auto-Generated Version Header - * DO NOT EDIT THIS FILE MANUALLY - Generated by build script - */ - -#ifndef VERSION_H -#define VERSION_H - -#define VERSION_MAJOR ${MAJOR} -#define VERSION_MINOR ${MINOR} -#define VERSION_PATCH ${NEW_PATCH} -#define VERSION_STRING "${MAJOR}.${MINOR}.${NEW_PATCH}" -#define VERSION_TAG "${NEW_VERSION}" - -/* Build information */ -#define BUILD_DATE "$(date +%Y-%m-%d)" -#define BUILD_TIME "$(date +%H:%M:%S)" -#define BUILD_TIMESTAMP "$(date '+%Y-%m-%d %H:%M:%S')" - -/* Git information */ -#define GIT_HASH "$(git rev-parse --short HEAD 2>/dev/null || echo 'unknown')" -#define GIT_BRANCH "$(git rev-parse --abbrev-ref HEAD 2>/dev/null || echo 'unknown')" - -/* Display versions */ -#define VERSION_DISPLAY "${NEW_VERSION}" -#define VERSION_FULL_DISPLAY "${NEW_VERSION} ($(date '+%Y-%m-%d %H:%M:%S'), $(git rev-parse --short HEAD 2>/dev/null || echo 'unknown'))" - -/* Version API functions */ -const char* get_version(void); -const char* get_version_full(void); -const char* get_build_info(void); - -#endif /* VERSION_H */ -EOF - -# Generate version.c implementation file -cat > src/version.c << EOF -/* - * Auto-Generated Version Implementation - * DO NOT EDIT THIS FILE MANUALLY - Generated by build script - */ - -#include "version.h" - -const char* get_version(void) { - return VERSION_TAG; -} - -const char* get_version_full(void) { - return VERSION_FULL_DISPLAY; -} - -const char* get_build_info(void) { - return "Built on " BUILD_DATE " at " BUILD_TIME " from commit " GIT_HASH " on branch " GIT_BRANCH; -} -EOF -``` - -### 3. Generate Version File for Other Languages - -**Python (`src/__version__.py`):** -```bash -cat > src/__version__.py << EOF -"""Auto-generated version file""" -__version__ = "${MAJOR}.${MINOR}.${NEW_PATCH}" -__version_tag__ = "${NEW_VERSION}" -__build_date__ = "$(date +%Y-%m-%d)" -__build_time__ = "$(date +%H:%M:%S)" -__git_hash__ = "$(git rev-parse --short HEAD 2>/dev/null || echo 'unknown')" -__git_branch__ = "$(git rev-parse --abbrev-ref HEAD 2>/dev/null || echo 'unknown')" -EOF -``` - -**JavaScript/Node.js (update `package.json`):** -```bash -# Update package.json version field -if [ -f package.json ]; then - sed -i "s/\"version\": \".*\"/\"version\": \"${MAJOR}.${MINOR}.${NEW_PATCH}\"/" package.json -fi -``` - -**Rust (update `Cargo.toml`):** -```bash -if [ -f Cargo.toml ]; then - sed -i "s/^version = \".*\"/version = \"${MAJOR}.${MINOR}.${NEW_PATCH}\"/" Cargo.toml -fi -``` - -**Go (generate `version.go`):** -```bash -cat > version.go << EOF -// Auto-generated version file -package main - -const ( - VersionMajor = ${MAJOR} - VersionMinor = ${MINOR} - VersionPatch = ${NEW_PATCH} - VersionString = "${MAJOR}.${MINOR}.${NEW_PATCH}" - VersionTag = "${NEW_VERSION}" - BuildDate = "$(date +%Y-%m-%d)" - BuildTime = "$(date +%H:%M:%S)" - GitHash = "$(git rev-parse --short HEAD 2>/dev/null || echo 'unknown')" - GitBranch = "$(git rev-parse --abbrev-ref HEAD 2>/dev/null || echo 'unknown')" -) -EOF -``` - -**Java (generate `Version.java`):** -```bash -cat > src/main/java/Version.java << EOF -// Auto-generated version class -public class Version { - public static final int VERSION_MAJOR = ${MAJOR}; - public static final int VERSION_MINOR = ${MINOR}; - public static final int VERSION_PATCH = ${NEW_PATCH}; - public static final String VERSION_STRING = "${MAJOR}.${MINOR}.${NEW_PATCH}"; - public static final String VERSION_TAG = "${NEW_VERSION}"; - public static final String BUILD_DATE = "$(date +%Y-%m-%d)"; - public static final String BUILD_TIME = "$(date +%H:%M:%S)"; - public static final String GIT_HASH = "$(git rev-parse --short HEAD 2>/dev/null || echo 'unknown')"; - public static final String GIT_BRANCH = "$(git rev-parse --abbrev-ref HEAD 2>/dev/null || echo 'unknown')"; -} -EOF -``` - -### 4. Integrate into Build Targets -Call `increment_version` before your main build commands: - -```bash -build_library() { - increment_version - echo "[INFO] Building library..." - # Your actual build commands here - make clean && make -} - -build_release() { - increment_version - echo "[INFO] Building release..." - # Your release build commands -} - -build_package() { - increment_version - echo "[INFO] Building package..." - # Your packaging commands -} -``` - -### 5. Update .gitignore -Add generated version files to `.gitignore`: - -```gitignore -# Auto-generated version files -src/version.h -src/version.c -src/__version__.py -version.go -src/main/java/Version.java -VERSION -``` - -### 6. Update Build System Files - -**For Makefile projects:** -```makefile -# Add version.c to your source files -SOURCES = main.c utils.c version.c -``` - -**For CMake projects:** -```cmake -# Add version files to your target -target_sources(your_target PRIVATE src/version.c) -``` - -**For Node.js projects:** -```json -{ - "scripts": { - "build": "node build.js && increment_version", - "version": "node -e \"console.log(require('./package.json').version)\"" - } -} -``` - -### 7. Create Initial Version Tag -```bash -# Start with initial version -git tag v0.1.0 -``` - -## Usage Pattern -```bash -./build.sh # v0.1.0 → v0.1.1 -./build.sh release # v0.1.1 → v0.1.2 -./build.sh package # v0.1.2 → v0.1.3 -``` - -## Manual Version Control - -### Major/Minor Version Bumps -```bash -# For feature releases (minor bump) -git tag v0.2.0 # Next build: v0.2.1 - -# For breaking changes (major bump) -git tag v1.0.0 # Next build: v1.0.1 -``` - -### Version Reset -```bash -# Delete incorrect tags (if needed) -git tag -d v0.2.1 -git push origin --delete v0.2.1 # If pushed to remote - -# Create correct base version -git tag v0.2.0 - -# Next build will create v0.2.1 -``` - -## Example Build Script Template -```bash -#!/bin/bash -set -e - -# Colors for output -RED='\033[0;31m' -GREEN='\033[0;32m' -YELLOW='\033[1;33m' -BLUE='\033[0;34m' -NC='\033[0m' - -print_status() { echo -e "${BLUE}[INFO]${NC} $1"; } -print_success() { echo -e "${GREEN}[SUCCESS]${NC} $1"; } -print_warning() { echo -e "${YELLOW}[WARNING]${NC} $1"; } -print_error() { echo -e "${RED}[ERROR]${NC} $1"; } - -# Insert increment_version function here - -case "${1:-build}" in - build) - increment_version - print_status "Building project..." - # Your build commands - ;; - clean) - print_status "Cleaning build artifacts..." - # Your clean commands - ;; - test) - print_status "Running tests..." - # Your test commands (no version increment) - ;; - release) - increment_version - print_status "Building release..." - # Your release commands - ;; - *) - echo "Usage: $0 {build|clean|test|release}" - exit 1 - ;; -esac -``` - -## Benefits -1. **Zero maintenance** - No manual version editing -2. **Build traceability** - Every build has unique version + metadata -3. **Git integration** - Automatic version tags -4. **Language agnostic** - Adapt generation for any language -5. **CI/CD friendly** - Works in automated environments -6. **Rollback friendly** - Easy to revert to previous versions - -## Troubleshooting - -### Version Not Incrementing -- Ensure you're in a git repository -- Check that git tags exist: `git tag --list` -- Verify tag format matches `v*.*.*` pattern - -### Tag Already Exists -If a tag already exists, the build continues with existing version: -``` -[WARNING] Tag v0.2.1 already exists - using existing version -``` - -### Missing Git Information -If git is unavailable, version files show "unknown" for git hash and branch. diff --git a/LIBRARY_USAGE.md b/LIBRARY_USAGE.md deleted file mode 100644 index 73f34a77..00000000 --- a/LIBRARY_USAGE.md +++ /dev/null @@ -1,319 +0,0 @@ -# NOSTR Core Library - Usage Guide - -## Overview - -The NOSTR Core Library (`libnostr_core`) is a self-contained, exportable C library for NOSTR protocol implementation. It requires **no external cryptographic dependencies** (no OpenSSL, no libwally) and can be easily integrated into other projects. - -## Key Features - -- **Self-Contained Crypto**: All cryptographic operations implemented from scratch -- **Zero External Dependencies**: Only requires standard C library, cJSON, and libwebsockets -- **Cross-Platform**: Builds on Linux, macOS, Windows (with appropriate toolchain) -- **NIP-06 Compliant**: Proper BIP39/BIP32 implementation for key derivation -- **Thread-Safe**: Core cryptographic functions are stateless and thread-safe -- **Easy Integration**: Simple C API with clear error handling - -## File Structure for Export - -### Core Library Files (Required) -``` -libnostr_core/ -├── nostr_core.h # Main public API header -├── nostr_core.c # Core implementation -├── nostr_crypto.h # Crypto implementation header -├── nostr_crypto.c # Self-contained crypto implementation -├── Makefile # Build configuration -└── cjson/ # JSON library (can be replaced with system cJSON) - ├── cJSON.h - └── cJSON.c -``` - -### Optional Files -``` -├── examples/ # Usage examples (helpful for integration) -├── LIBRARY_USAGE.md # This usage guide -├── SELF_CONTAINED_CRYPTO.md # Crypto implementation details -└── CROSS_PLATFORM_GUIDE.md # Platform-specific build notes -``` - -## Integration Methods - -### Method 1: Static Library Integration - -1. **Copy Required Files**: - ```bash - cp nostr_core.h nostr_core.c nostr_crypto.h nostr_crypto.c /path/to/your/project/ - cp -r cjson/ /path/to/your/project/ - ``` - -2. **Build Static Library**: - ```bash - gcc -c -fPIC nostr_core.c nostr_crypto.c cjson/cJSON.c - ar rcs libnostr_core.a nostr_core.o nostr_crypto.o cJSON.o - ``` - -3. **Link in Your Project**: - ```bash - gcc your_project.c -L. -lnostr_core -lm -o your_project - ``` - -### Method 2: Direct Source Integration - -Simply include the source files directly in your project: - -```c -// In your project -#include "nostr_core.h" - -// Compile with: -// gcc your_project.c nostr_core.c nostr_crypto.c cjson/cJSON.c -lm -``` - -### Method 3: Shared Library Integration - -1. **Build Shared Library**: - ```bash - make libnostr_core.so - ``` - -2. **Install System-Wide** (optional): - ```bash - sudo cp libnostr_core.so /usr/local/lib/ - sudo cp nostr_core.h /usr/local/include/ - sudo ldconfig - ``` - -3. **Use in Projects**: - ```bash - gcc your_project.c -lnostr_core -lm - ``` - -## Building the Library - -### Using the Provided Build Script - -The library includes an automated build script that handles all dependencies and creates a self-contained static library. - -**IMPORTANT**: The build script must be run from within the `nostr_core_lib` directory: - -```bash -# Correct usage: -cd nostr_core_lib -./build.sh - -# If you need to use it from your project directory: -cd nostr_core_lib -./build.sh -cd .. -gcc your_app.c nostr_core_lib/libnostr_core_x64.a -lz -ldl -lpthread -lm -o your_app -``` - -**Common Error**: Running `./nostr_core_lib/build.sh` from outside the library directory will fail with: -``` -[ERROR] Build script must be run from the nostr_core_lib directory -``` - -### Build Script Options - -```bash -# Auto-detect NIPs from your source code -./build.sh - -# Force specific NIPs -./build.sh --nips=1,6,19 - -# Build all available NIPs -./build.sh --nips=all - -# Build for specific architecture -./build.sh arm64 - -# Build with tests -./build.sh --tests - -# Get help -./build.sh --help -``` - -The build script automatically: -- Scans your `.c` files for `#include "nip*.h"` statements -- Compiles only the needed NIPs -- Creates a self-contained static library (`libnostr_core_x64.a`) -- Includes all dependencies (OpenSSL, curl, secp256k1, cJSON) - -## Basic Usage Example - -```c -#include "nostr_core.h" -#include -#include - -int main() { - // Initialize the library - if (nostr_init() != NOSTR_SUCCESS) { - fprintf(stderr, "Failed to initialize NOSTR library\n"); - return 1; - } - - // Generate a keypair - unsigned char private_key[32]; - unsigned char public_key[32]; - - if (nostr_generate_keypair(private_key, public_key) != NOSTR_SUCCESS) { - fprintf(stderr, "Failed to generate keypair\n"); - nostr_cleanup(); - return 1; - } - - // Convert to hex and bech32 - char private_hex[65], public_hex[65]; - char nsec[100], npub[100]; - - nostr_bytes_to_hex(private_key, 32, private_hex); - nostr_bytes_to_hex(public_key, 32, public_hex); - nostr_key_to_bech32(private_key, "nsec", nsec); - nostr_key_to_bech32(public_key, "npub", npub); - - printf("Private Key: %s\n", private_hex); - printf("Public Key: %s\n", public_hex); - printf("nsec: %s\n", nsec); - printf("npub: %s\n", npub); - - // Create and sign an event - cJSON* event = nostr_create_text_event("Hello NOSTR!", private_key); - if (event) { - char* event_json = cJSON_Print(event); - printf("Signed Event: %s\n", event_json); - free(event_json); - cJSON_Delete(event); - } - - // Cleanup - nostr_cleanup(); - return 0; -} -``` - -## Dependency Management - -### Required Dependencies -- **Standard C Library**: malloc, string functions, file I/O -- **Math Library**: `-lm` (for cryptographic calculations) -- **cJSON**: JSON parsing (included, or use system version) - -### Optional Dependencies -- **libwebsockets**: Only needed for relay communication functions -- **System cJSON**: Can replace bundled version - -### Minimal Integration (Crypto Only) -If you only need key generation and signing: - -```bash -# Build with minimal dependencies -gcc -DNOSTR_CRYPTO_ONLY your_project.c nostr_crypto.c -lm -``` - -## Cross-Platform Considerations - -### Linux -- Works out of the box with GCC -- Install build-essential: `sudo apt install build-essential` - -### macOS -- Works with Xcode command line tools -- May need: `xcode-select --install` - -### Windows -- Use MinGW-w64 or MSYS2 -- Or integrate with Visual Studio project - -### Embedded Systems -- Library is designed to work on resource-constrained systems -- No heap allocations in core crypto functions -- Stack usage is predictable and bounded - -## API Reference - -### Initialization -```c -int nostr_init(void); // Initialize library -void nostr_cleanup(void); // Cleanup resources -const char* nostr_strerror(int error); // Get error string -``` - -### Key Generation -```c -int nostr_generate_keypair(unsigned char* private_key, unsigned char* public_key); -int nostr_generate_mnemonic_and_keys(char* mnemonic, size_t mnemonic_size, - int account, unsigned char* private_key, - unsigned char* public_key); -int nostr_derive_keys_from_mnemonic(const char* mnemonic, int account, - unsigned char* private_key, unsigned char* public_key); -``` - -### Event Creation -```c -cJSON* nostr_create_text_event(const char* content, const unsigned char* private_key); -cJSON* nostr_create_profile_event(const char* name, const char* about, - const unsigned char* private_key); -int nostr_sign_event(cJSON* event, const unsigned char* private_key); -``` - -### Utilities -```c -void nostr_bytes_to_hex(const unsigned char* bytes, size_t len, char* hex); -int nostr_hex_to_bytes(const char* hex, unsigned char* bytes, size_t len); -int nostr_key_to_bech32(const unsigned char* key, const char* hrp, char* output); -nostr_input_type_t nostr_detect_input_type(const char* input); -``` - -## Error Handling - -All functions return standardized error codes: - -- `NOSTR_SUCCESS` (0): Operation successful -- `NOSTR_ERROR_INVALID_INPUT` (-1): Invalid parameters -- `NOSTR_ERROR_CRYPTO_FAILED` (-2): Cryptographic operation failed -- `NOSTR_ERROR_MEMORY_FAILED` (-3): Memory allocation failed -- `NOSTR_ERROR_IO_FAILED` (-4): File I/O operation failed -- `NOSTR_ERROR_NETWORK_FAILED` (-5): Network operation failed - -## Security Considerations - -1. **Private Key Handling**: Always clear private keys from memory when done -2. **Random Number Generation**: Uses `/dev/urandom` on Unix systems -3. **Memory Safety**: All buffers are bounds-checked -4. **Constant-Time Operations**: Critical crypto operations are timing-attack resistant - -## Testing Your Integration - -Use the provided examples to verify your integration: - -```bash -# Test key generation -./examples/simple_keygen - -# Test mnemonic functionality -./examples/mnemonic_generation - -# Test event creation -./examples/text_event - -# Test all functionality -./examples/utility_functions -``` - -## Support and Documentation - -- See `examples/` directory for comprehensive usage examples -- Check `SELF_CONTAINED_CRYPTO.md` for cryptographic implementation details -- Review `CROSS_PLATFORM_GUIDE.md` for platform-specific notes -- All functions are documented in `nostr_core.h` - -## License - -This library is designed to be freely integrable into other projects. Check the individual file headers for specific licensing information. - ---- - -**Quick Start**: Copy `nostr_core.h`, `nostr_core.c`, `nostr_crypto.h`, `nostr_crypto.c`, and the `cjson/` folder to your project, then compile with `-lm`. That's it! diff --git a/debug_nip04_comparison.js b/debug_nip04_comparison.js deleted file mode 100644 index 7db6f9d1..00000000 --- a/debug_nip04_comparison.js +++ /dev/null @@ -1,106 +0,0 @@ -import { bytesToHex, hexToBytes, randomBytes } from '@noble/hashes/utils' -import { secp256k1 } from '@noble/curves/secp256k1' -import { cbc } from '@noble/ciphers/aes' -import { base64 } from '@scure/base' - -// UTF-8 encoder/decoder -const utf8Encoder = new TextEncoder() -const utf8Decoder = new TextDecoder() - -function getNormalizedX(key) { - return key.slice(1, 33) -} - -function encrypt(secretKey, pubkey, text) { - console.log(`[JS] Encrypting "${text}" using sk1 -> pk2`) - console.log(`[JS] Private Key: ${secretKey}`) - console.log(`[JS] Public Key: ${pubkey}`) - - // Step 1: Get shared secret - const key = secp256k1.getSharedSecret(secretKey, '02' + pubkey) - console.log(`[JS] Shared Secret: ${bytesToHex(key)}`) - - // Step 2: Normalize key (remove first byte, keep next 32) - const normalizedKey = getNormalizedX(key) - console.log(`[JS] Normalized Key: ${bytesToHex(normalizedKey)}`) - - // Step 3: Generate random IV - const iv = randomBytes(16) - console.log(`[JS] IV: ${bytesToHex(iv)}`) - - // Step 4: Encode plaintext to UTF-8 - const plaintext = utf8Encoder.encode(text) - console.log(`[JS] UTF-8 Plaintext: ${bytesToHex(plaintext)}`) - - // Step 5: AES-CBC encryption - const ciphertext = cbc(normalizedKey, iv).encrypt(plaintext) - console.log(`[JS] Raw Ciphertext: ${bytesToHex(new Uint8Array(ciphertext))}`) - - // Step 6: Base64 encoding - const ctb64 = base64.encode(new Uint8Array(ciphertext)) - const ivb64 = base64.encode(new Uint8Array(iv.buffer)) - - const result = `${ctb64}?iv=${ivb64}` - console.log(`[JS] Encrypted Result: ${result}`) - - return result -} - -function decrypt(secretKey, pubkey, data) { - console.log(`[JS] Decrypting "${data}" using sk2 + pk1`) - console.log(`[JS] Private Key: ${secretKey}`) - console.log(`[JS] Public Key: ${pubkey}`) - - // Step 1: Parse format - const [ctb64, ivb64] = data.split('?iv=') - - // Step 2: Get shared secret - const key = secp256k1.getSharedSecret(secretKey, '02' + pubkey) - console.log(`[JS] Shared Secret: ${bytesToHex(key)}`) - - // Step 3: Normalize key - const normalizedKey = getNormalizedX(key) - console.log(`[JS] Normalized Key: ${bytesToHex(normalizedKey)}`) - - // Step 4: Base64 decode - const iv = base64.decode(ivb64) - const ciphertext = base64.decode(ctb64) - console.log(`[JS] IV: ${bytesToHex(iv)}`) - console.log(`[JS] Raw Ciphertext: ${bytesToHex(ciphertext)}`) - - // Step 5: AES-CBC decryption - const plaintext = cbc(normalizedKey, iv).decrypt(ciphertext) - console.log(`[JS] Decrypted Plaintext: ${bytesToHex(plaintext)}`) - - // Step 6: UTF-8 decode - const result = utf8Decoder.decode(plaintext) - console.log(`[JS] UTF-8 Decoded: "${result}"`) - - return result -} - -// Test with exact vectors -async function main() { - console.log("=== NIP-04 DEBUG COMPARISON (JavaScript) ===") - - const sk1 = "91ba716fa9e7ea2fcbad360cf4f8e0d312f73984da63d90f524ad61a6a1e7dbe" - const pk1 = "b38ce15d3d9874ee710dfabb7ff9801b1e0e20aace6e9a1a05fa7482a04387d1" - const sk2 = "96f6fa197aa07477ab88f6981118466ae3a982faab8ad5db9d5426870c73d220" - const pk2 = "dcb33a629560280a0ee3b6b99b68c044fe8914ad8a984001ebf6099a9b474dc3" - const plaintext = "nanana" - const expectedCiphertext = "d6Joav5EciPI9hdHw31vmQ==?iv=fWs5rfv2+532arG/k83kcA==" - - console.log("\n--- ENCRYPTION TEST ---") - const encrypted = encrypt(sk1, pk2, plaintext) - - console.log("\n--- DECRYPTION TEST ---") - const decrypted = decrypt(sk2, pk1, expectedCiphertext) - - console.log("\n--- RESULTS ---") - console.log(`Encryption Success: Generated ciphertext`) - console.log(`Decryption Success: ${decrypted === plaintext}`) - console.log(`Expected: "${plaintext}"`) - console.log(`Got: "${decrypted}"`) -} - -main().catch(console.error) diff --git a/debug_nip44_comparison.js b/debug_nip44_comparison.js deleted file mode 100644 index 39eac15f..00000000 --- a/debug_nip44_comparison.js +++ /dev/null @@ -1,280 +0,0 @@ -import { bytesToHex, hexToBytes, randomBytes } from '@noble/hashes/utils' -import { secp256k1 } from '@noble/curves/secp256k1' -import { extract as hkdf_extract, expand as hkdf_expand } from '@noble/hashes/hkdf' -import { hmac } from '@noble/hashes/hmac' -import { sha256 } from '@noble/hashes/sha256' -import { concatBytes } from '@noble/hashes/utils' -import { base64 } from '@scure/base' -import { chacha20 } from '@noble/ciphers/chacha' -import { equalBytes } from '@noble/ciphers/utils' - -// UTF-8 encoder/decoder -const utf8Encoder = new TextEncoder() -const utf8Decoder = new TextDecoder() - -const minPlaintextSize = 0x0001 // 1b msg => padded to 32b -const maxPlaintextSize = 0xffff // 65535 (64kb-1) => padded to 64kb - -function getConversationKey(privkeyA, pubkeyB) { - console.log(`[JS] Computing conversation key`) - console.log(`[JS] Private Key A: ${privkeyA}`) - console.log(`[JS] Public Key B: ${pubkeyB}`) - - const sharedX = secp256k1.getSharedSecret(privkeyA, '02' + pubkeyB).subarray(1, 33) - console.log(`[JS] Shared Secret: ${bytesToHex(sharedX)}`) - - const conversationKey = hkdf_extract(sha256, sharedX, 'nip44-v2') - console.log(`[JS] Conversation Key: ${bytesToHex(conversationKey)}`) - - return conversationKey -} - -function getMessageKeys(conversationKey, nonce) { - console.log(`[JS] Deriving message keys`) - console.log(`[JS] Conversation Key: ${bytesToHex(conversationKey)}`) - console.log(`[JS] Nonce: ${bytesToHex(nonce)}`) - - const keys = hkdf_expand(sha256, conversationKey, nonce, 76) - const result = { - chacha_key: keys.subarray(0, 32), - chacha_nonce: keys.subarray(32, 44), - hmac_key: keys.subarray(44, 76), - } - - console.log(`[JS] ChaCha20 Key: ${bytesToHex(result.chacha_key)}`) - console.log(`[JS] ChaCha20 Nonce: ${bytesToHex(result.chacha_nonce)}`) - console.log(`[JS] HMAC Key: ${bytesToHex(result.hmac_key)}`) - - return result -} - -function calcPaddedLen(len) { - if (!Number.isSafeInteger(len) || len < 1) throw new Error('expected positive integer') - if (len <= 32) return 32 - const nextPower = 1 << (Math.floor(Math.log2(len - 1)) + 1) - const chunk = nextPower <= 256 ? 32 : nextPower / 8 - return chunk * (Math.floor((len - 1) / chunk) + 1) -} - -function writeU16BE(num) { - if (!Number.isSafeInteger(num) || num < minPlaintextSize || num > maxPlaintextSize) - throw new Error('invalid plaintext size: must be between 1 and 65535 bytes') - const arr = new Uint8Array(2) - new DataView(arr.buffer).setUint16(0, num, false) - return arr -} - -function pad(plaintext) { - console.log(`[JS] Padding plaintext: "${plaintext}"`) - const unpadded = utf8Encoder.encode(plaintext) - const unpaddedLen = unpadded.length - console.log(`[JS] Unpadded length: ${unpaddedLen}`) - console.log(`[JS] Unpadded bytes: ${bytesToHex(unpadded)}`) - - const prefix = writeU16BE(unpaddedLen) - console.log(`[JS] Length prefix: ${bytesToHex(prefix)}`) - - const paddedLen = calcPaddedLen(unpaddedLen) - console.log(`[JS] Calculated padded length: ${paddedLen}`) - - const suffix = new Uint8Array(paddedLen - unpaddedLen) - console.log(`[JS] Padding suffix length: ${suffix.length}`) - - const result = concatBytes(prefix, unpadded, suffix) - console.log(`[JS] Final padded: ${bytesToHex(result)}`) - - return result -} - -function unpad(padded) { - console.log(`[JS] Unpadding data: ${bytesToHex(padded)}`) - const unpaddedLen = new DataView(padded.buffer).getUint16(0) - console.log(`[JS] Read length from prefix: ${unpaddedLen}`) - - const unpadded = padded.subarray(2, 2 + unpaddedLen) - console.log(`[JS] Extracted unpadded: ${bytesToHex(unpadded)}`) - - if ( - unpaddedLen < minPlaintextSize || - unpaddedLen > maxPlaintextSize || - unpadded.length !== unpaddedLen || - padded.length !== 2 + calcPaddedLen(unpaddedLen) - ) { - console.log(`[JS] Padding validation failed:`) - console.log(`[JS] unpaddedLen: ${unpaddedLen} (should be ${minPlaintextSize}-${maxPlaintextSize})`) - console.log(`[JS] unpadded.length: ${unpadded.length}`) - console.log(`[JS] padded.length: ${padded.length}`) - console.log(`[JS] expected padded length: ${2 + calcPaddedLen(unpaddedLen)}`) - throw new Error('invalid padding') - } - - const result = utf8Decoder.decode(unpadded) - console.log(`[JS] Decoded plaintext: "${result}"`) - return result -} - -function hmacAad(key, message, aad) { - if (aad.length !== 32) throw new Error('AAD associated data must be 32 bytes') - console.log(`[JS] Computing HMAC`) - console.log(`[JS] HMAC Key: ${bytesToHex(key)}`) - console.log(`[JS] AAD: ${bytesToHex(aad)}`) - console.log(`[JS] Message: ${bytesToHex(message)}`) - - const combined = concatBytes(aad, message) - console.log(`[JS] Combined AAD+Message: ${bytesToHex(combined)}`) - - const result = hmac(sha256, key, combined) - console.log(`[JS] HMAC Result: ${bytesToHex(result)}`) - - return result -} - -function decodePayload(payload) { - console.log(`[JS] Decoding payload: ${payload}`) - if (typeof payload !== 'string') throw new Error('payload must be a valid string') - const plen = payload.length - if (plen < 132 || plen > 87472) throw new Error('invalid payload length: ' + plen) - if (payload[0] === '#') throw new Error('unknown encryption version') - - let data - try { - data = base64.decode(payload) - } catch (error) { - throw new Error('invalid base64: ' + error.message) - } - - console.log(`[JS] Base64 decoded data: ${bytesToHex(data)}`) - const dlen = data.length - if (dlen < 99 || dlen > 65603) throw new Error('invalid data length: ' + dlen) - const vers = data[0] - if (vers !== 2) throw new Error('unknown encryption version ' + vers) - - const result = { - nonce: data.subarray(1, 33), - ciphertext: data.subarray(33, -32), - mac: data.subarray(-32), - } - - console.log(`[JS] Version: ${vers}`) - console.log(`[JS] Nonce: ${bytesToHex(result.nonce)}`) - console.log(`[JS] Ciphertext: ${bytesToHex(result.ciphertext)}`) - console.log(`[JS] MAC: ${bytesToHex(result.mac)}`) - - return result -} - -function encrypt(plaintext, conversationKey, nonce = randomBytes(32)) { - console.log(`[JS] ===== ENCRYPTING "${plaintext}" =====`) - const { chacha_key, chacha_nonce, hmac_key } = getMessageKeys(conversationKey, nonce) - const padded = pad(plaintext) - - console.log(`[JS] Encrypting with ChaCha20`) - const ciphertext = chacha20(chacha_key, chacha_nonce, padded) - console.log(`[JS] ChaCha20 ciphertext: ${bytesToHex(ciphertext)}`) - - const mac = hmacAad(hmac_key, ciphertext, nonce) - - console.log(`[JS] Building final payload`) - const payload = concatBytes(new Uint8Array([2]), nonce, ciphertext, mac) - console.log(`[JS] Raw payload: ${bytesToHex(payload)}`) - - const result = base64.encode(payload) - console.log(`[JS] Base64 encoded result: ${result}`) - - return result -} - -function decrypt(payload, conversationKey) { - console.log(`[JS] ===== DECRYPTING "${payload}" =====`) - const { nonce, ciphertext, mac } = decodePayload(payload) - const { chacha_key, chacha_nonce, hmac_key } = getMessageKeys(conversationKey, nonce) - - const calculatedMac = hmacAad(hmac_key, ciphertext, nonce) - console.log(`[JS] MAC verification`) - console.log(`[JS] Received MAC: ${bytesToHex(mac)}`) - console.log(`[JS] Calculated MAC: ${bytesToHex(calculatedMac)}`) - - if (!equalBytes(calculatedMac, mac)) { - console.log(`[JS] MAC MISMATCH!`) - throw new Error('invalid MAC') - } - console.log(`[JS] MAC verification PASSED`) - - console.log(`[JS] Decrypting with ChaCha20`) - const padded = chacha20(chacha_key, chacha_nonce, ciphertext) - console.log(`[JS] ChaCha20 decrypted: ${bytesToHex(padded)}`) - - const result = unpad(padded) - console.log(`[JS] Final decrypted plaintext: "${result}"`) - - return result -} - -// Test with exact vectors that are failing in C -async function main() { - console.log("=== NIP-44 DEBUG COMPARISON (JavaScript) ===") - - // Test vector 1: single char 'a' - MATCHES nostr-tools official vector - const test1 = { - sec1: "0000000000000000000000000000000000000000000000000000000000000001", - sec2: "0000000000000000000000000000000000000000000000000000000000000002", - plaintext: "a", - expectedPayload: "AgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABee0G5VSK0/9YypIObAtDKfYEAjD35uVkHyB0F4DwrcNaCXlCWZKaArsGrY6M9wnuTMxWfp1RTN9Xga8no+kF5Vsb" - } - - console.log("\n=== TEST 1: Single char 'a' ===") - - // Step 1: Get conversation key using sender's private key + recipient's public key - const sec1Bytes = hexToBytes(test1.sec1) - const sec2Bytes = hexToBytes(test1.sec2) - const pub2 = bytesToHex(secp256k1.getPublicKey(sec2Bytes, false).subarray(1, 33)) // x-only - console.log(`[JS] Derived pub2 from sec2: ${pub2}`) - - const conversationKey1 = getConversationKey(test1.sec1, pub2) - - // Step 2: Try to decrypt the expected payload (this should work if our C code matches) - console.log("\n--- DECRYPTION TEST ---") - try { - const decrypted1 = decrypt(test1.expectedPayload, conversationKey1) - console.log(`✅ Decryption SUCCESS: "${decrypted1}"`) - console.log(`✅ Match: ${decrypted1 === test1.plaintext}`) - } catch (error) { - console.log(`❌ Decryption FAILED: ${error.message}`) - } - - // Step 3: Generate fresh encryption to compare format - console.log("\n--- ENCRYPTION TEST (with random nonce) ---") - const encrypted1 = encrypt(test1.plaintext, conversationKey1) - console.log(`Generated payload: ${encrypted1}`) - - // Step 4: Decrypt our own encryption (round-trip test) - console.log("\n--- ROUND-TRIP TEST ---") - try { - const roundTrip1 = decrypt(encrypted1, conversationKey1) - console.log(`✅ Round-trip SUCCESS: "${roundTrip1}"`) - console.log(`✅ Match: ${roundTrip1 === test1.plaintext}`) - } catch (error) { - console.log(`❌ Round-trip FAILED: ${error.message}`) - } - - // Test the other failing vectors too - console.log("\n=== TEST 2: Emoji ===") - const test2 = { - sec1: "0000000000000000000000000000000000000000000000000000000000000002", - sec2: "0000000000000000000000000000000000000000000000000000000000000001", - plaintext: "🍕🫃", - expectedPayload: "AvAAAAAAAAAAAAAAAAAAAPAAAAAAAAAAAAAAAAAAAAAPSKSK6is9ngkX2+cSq85Th16oRTISAOfhStnixqZziKMDvB0QQzgFZdjLTPicCJaV8nDITO+QfaQ61+KbWQIOO2Yj" - } - - const pub1 = bytesToHex(secp256k1.getPublicKey(hexToBytes(test2.sec2), false).subarray(1, 33)) - const conversationKey2 = getConversationKey(test2.sec1, pub1) - - try { - const decrypted2 = decrypt(test2.expectedPayload, conversationKey2) - console.log(`✅ Test 2 SUCCESS: "${decrypted2}"`) - } catch (error) { - console.log(`❌ Test 2 FAILED: ${error.message}`) - } -} - -main().catch(console.error) diff --git a/example_basic.c b/example_basic.c deleted file mode 100644 index c41f0f65..00000000 --- a/example_basic.c +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Example: Basic NOSTR functionality - * This example shows auto-detection working with selective includes - */ - -#include "nostr_core/nip001.h" // Basic protocol -#include "nostr_core/nip006.h" // Key generation (will be created next) -#include "nostr_core/nip019.h" // Bech32 encoding (will be created next) - -#include - -int main() { - printf("NOSTR Core Library - Basic Example\n"); - - // Initialize library - if (nostr_init() != 0) { - printf("Failed to initialize NOSTR library\n"); - return 1; - } - - printf("Library initialized successfully!\n"); - - // Generate keypair (from NIP-006) - // unsigned char private_key[32], public_key[32]; - // nostr_generate_keypair(private_key, public_key); - - // Convert to bech32 (from NIP-019) - // char nsec[100]; - // nostr_key_to_bech32(private_key, "nsec", nsec); - - // Create basic event (from NIP-001) - // cJSON* event = nostr_create_and_sign_event(1, "Hello Nostr!", NULL, private_key, 0); - - printf("Example completed - the build script should detect NIPs: 001, 006, 019\n"); - - // Cleanup - nostr_cleanup(); - - return 0; -} diff --git a/example_modular_nips.c b/example_modular_nips.c deleted file mode 100644 index 8e76a44f..00000000 --- a/example_modular_nips.c +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Example demonstrating modular NIP usage - * Shows how different NIPs can be used independently - */ - -#include "nostr_core/nip001.h" // Basic protocol -#include "nostr_core/nip005.h" // NIP-05 DNS verification -#include "nostr_core/nip006.h" // Key derivation -#include "nostr_core/nip011.h" // Relay information -#include "nostr_core/nip013.h" // Proof of work -#include "nostr_core/nip019.h" // Bech32 encoding -#include "nostr_core/utils.h" // Utility functions -#include -#include - -int main() { - printf("=== Modular NOSTR Core Library Demo ===\n\n"); - - // Initialize the library - if (nostr_init() != NOSTR_SUCCESS) { - printf("Failed to initialize NOSTR library\n"); - return 1; - } - - // Test NIP-006: Key generation and detection - printf("1. NIP-006: Key Generation and Input Detection\n"); - unsigned char private_key[32], public_key[32]; - - if (nostr_generate_keypair(private_key, public_key) == NOSTR_SUCCESS) { - char private_hex[65], public_hex[65]; - nostr_bytes_to_hex(private_key, 32, private_hex); - nostr_bytes_to_hex(public_key, 32, public_hex); - - printf(" Generated keypair:\n"); - printf(" Private: %s\n", private_hex); - printf(" Public: %s\n", public_hex); - - // Test input type detection - nostr_input_type_t type = nostr_detect_input_type(private_hex); - printf(" Input type: %s\n", - type == NOSTR_INPUT_NSEC_HEX ? "NSEC_HEX" : - type == NOSTR_INPUT_NSEC_BECH32 ? "NSEC_BECH32" : - type == NOSTR_INPUT_MNEMONIC ? "MNEMONIC" : "UNKNOWN"); - } - - // Test NIP-019: Bech32 encoding - printf("\n2. NIP-019: Bech32 Encoding\n"); - char bech32_nsec[200], bech32_npub[200]; - - if (nostr_key_to_bech32(private_key, "nsec", bech32_nsec) == NOSTR_SUCCESS) { - printf(" nsec: %s\n", bech32_nsec); - } - - if (nostr_key_to_bech32(public_key, "npub", bech32_npub) == NOSTR_SUCCESS) { - printf(" npub: %s\n", bech32_npub); - } - - // Test NIP-001: Event creation - printf("\n3. NIP-001: Event Creation\n"); - cJSON* event = nostr_create_and_sign_event(1, "Hello from modular NOSTR!", NULL, private_key, 0); - if (event) { - char* event_json = cJSON_Print(event); - printf(" Created event: %s\n", event_json); - free(event_json); - cJSON_Delete(event); - } - - // Test NIP-013: Proof of Work (light test) - printf("\n4. NIP-013: Proof of Work\n"); - cJSON* pow_event = nostr_create_and_sign_event(1, "PoW test message", NULL, private_key, 0); - if (pow_event) { - printf(" Adding PoW (target difficulty: 4)...\n"); - int result = nostr_add_proof_of_work(pow_event, private_key, 4, 100000, 10000, 5000, NULL, NULL); - if (result == NOSTR_SUCCESS) { - cJSON* id_item = cJSON_GetObjectItem(pow_event, "id"); - if (id_item) { - printf(" PoW success! Event ID: %s\n", cJSON_GetStringValue(id_item)); - } - } else { - printf(" PoW failed or timeout\n"); - } - cJSON_Delete(pow_event); - } - - // Test NIP-005: DNS verification (parse only - no network call in example) - printf("\n5. NIP-005: DNS Identifier Parsing\n"); - const char* test_json = "{\"names\":{\"test\":\"1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef\"}}"; - char found_pubkey[65]; - - int result = nostr_nip05_parse_well_known(test_json, "test", found_pubkey, NULL, NULL); - if (result == NOSTR_SUCCESS) { - printf(" Parsed pubkey from test JSON: %s\n", found_pubkey); - } - - // Test NIP-011: Just show the structure exists - printf("\n6. NIP-011: Relay Information Structure\n"); - printf(" Relay info structure available for fetching relay metadata\n"); - printf(" (Network calls not performed in this example)\n"); - - printf("\n=== All modular NIPs working! ===\n"); - - nostr_cleanup(); - return 0; -} diff --git a/rfc8439.txt b/rfc8439.txt deleted file mode 100644 index c50c8624..00000000 --- a/rfc8439.txt +++ /dev/null @@ -1,2579 +0,0 @@ - - - - - - -Internet Research Task Force (IRTF) Y. Nir -Request for Comments: 8439 Dell EMC -Obsoletes: 7539 A. Langley -Category: Informational Google, Inc. -ISSN: 2070-1721 June 2018 - - - ChaCha20 and Poly1305 for IETF Protocols - -Abstract - - This document defines the ChaCha20 stream cipher as well as the use - of the Poly1305 authenticator, both as stand-alone algorithms and as - a "combined mode", or Authenticated Encryption with Associated Data - (AEAD) algorithm. - - RFC 7539, the predecessor of this document, was meant to serve as a - stable reference and an implementation guide. It was a product of - the Crypto Forum Research Group (CFRG). This document merges the - errata filed against RFC 7539 and adds a little text to the Security - Considerations section. - -Status of This Memo - - This document is not an Internet Standards Track specification; it is - published for informational purposes. - - This document is a product of the Internet Research Task Force - (IRTF). The IRTF publishes the results of Internet-related research - and development activities. These results might not be suitable for - deployment. This RFC represents the consensus of the Crypto Forum - Research Group of the Internet Research Task Force (IRTF). Documents - approved for publication by the IRSG are not candidates for any level - of Internet Standard; see Section 2 of RFC 7841. - - Information about the current status of this document, any errata, - and how to provide feedback on it may be obtained at - https://www.rfc-editor.org/info/rfc8439. - - - - - - - - - - - - - -Nir & Langley Informational [Page 1] - -RFC 8439 ChaCha20 & Poly1305 June 2018 - - -Copyright Notice - - Copyright (c) 2018 IETF Trust and the persons identified as the - document authors. All rights reserved. - - This document is subject to BCP 78 and the IETF Trust's Legal - Provisions Relating to IETF Documents - (https://trustee.ietf.org/license-info) in effect on the date of - publication of this document. Please review these documents - carefully, as they describe your rights and restrictions with respect - to this document. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Nir & Langley Informational [Page 2] - -RFC 8439 ChaCha20 & Poly1305 June 2018 - - -Table of Contents - - 1. Introduction . . . . . . . . . . . . . . . . . . . . . . . . 4 - 1.1. Conventions Used in This Document . . . . . . . . . . . . 5 - 2. The Algorithms . . . . . . . . . . . . . . . . . . . . . . . 5 - 2.1. The ChaCha Quarter Round . . . . . . . . . . . . . . . . 5 - 2.1.1. Test Vector for the ChaCha Quarter Round . . . . . . 6 - 2.2. A Quarter Round on the ChaCha State . . . . . . . . . . . 6 - 2.2.1. Test Vector for the Quarter Round on the ChaCha State 7 - 2.3. The ChaCha20 Block Function . . . . . . . . . . . . . . . 7 - 2.3.1. The ChaCha20 Block Function in Pseudocode . . . . . . 9 - 2.3.2. Test Vector for the ChaCha20 Block Function . . . . . 10 - 2.4. The ChaCha20 Encryption Algorithm . . . . . . . . . . . . 11 - 2.4.1. The ChaCha20 Encryption Algorithm in Pseudocode . . . 12 - 2.4.2. Example and Test Vector for the ChaCha20 Cipher . . . 12 - 2.5. The Poly1305 Algorithm . . . . . . . . . . . . . . . . . 14 - 2.5.1. The Poly1305 Algorithms in Pseudocode . . . . . . . . 16 - 2.5.2. Poly1305 Example and Test Vector . . . . . . . . . . 17 - 2.6. Generating the Poly1305 Key Using ChaCha20 . . . . . . . 18 - 2.6.1. Poly1305 Key Generation in Pseudocode . . . . . . . . 19 - 2.6.2. Poly1305 Key Generation Test Vector . . . . . . . . . 19 - 2.7. A Pseudorandom Function for Crypto Suites Based on - ChaCha/Poly1305 . . . . . . . . . . . . . . . . . . . . . 20 - 2.8. AEAD Construction . . . . . . . . . . . . . . . . . . . . 20 - 2.8.1. Pseudocode for the AEAD Construction . . . . . . . . 23 - 2.8.2. Example and Test Vector for AEAD_CHACHA20_POLY1305 . 23 - 3. Implementation Advice . . . . . . . . . . . . . . . . . . . . 25 - 4. Security Considerations . . . . . . . . . . . . . . . . . . . 26 - 5. IANA Considerations . . . . . . . . . . . . . . . . . . . . . 27 - 6. References . . . . . . . . . . . . . . . . . . . . . . . . . 27 - 6.1. Normative References . . . . . . . . . . . . . . . . . . 27 - 6.2. Informative References . . . . . . . . . . . . . . . . . 28 - Appendix A. Additional Test Vectors . . . . . . . . . . . . . . 30 - A.1. The ChaCha20 Block Functions . . . . . . . . . . . . . . 30 - A.2. ChaCha20 Encryption . . . . . . . . . . . . . . . . . . . 33 - A.3. Poly1305 Message Authentication Code . . . . . . . . . . 36 - A.4. Poly1305 Key Generation Using ChaCha20 . . . . . . . . . 41 - A.5. ChaCha20-Poly1305 AEAD Decryption . . . . . . . . . . . . 42 - Appendix B. Performance Measurements of ChaCha20 . . . . . . . . 45 - Acknowledgements . . . . . . . . . . . . . . . . . . . . . . . . 46 - Authors' Addresses . . . . . . . . . . . . . . . . . . . . . . . 46 - - - - - - - - - - -Nir & Langley Informational [Page 3] - -RFC 8439 ChaCha20 & Poly1305 June 2018 - - -1. Introduction - - The Advanced Encryption Standard (AES -- [FIPS-197]) has become the - gold standard in encryption. Its efficient design, widespread - implementation, and hardware support allow for high performance in - many areas. On most modern platforms, AES is anywhere from four to - ten times as fast as the previous most-used cipher, Triple Data - Encryption Standard (3DES -- [SP800-67]), which makes it not only the - best choice, but the only practical choice. - - There are several problems with this. If future advances in - cryptanalysis reveal a weakness in AES, users will be in an - unenviable position. With the only other widely supported cipher - being the much slower 3DES, it is not feasible to reconfigure - deployments to use 3DES. [Standby-Cipher] describes this issue and - the need for a standby cipher in greater detail. Another problem is - that while AES is very fast on dedicated hardware, its performance on - platforms that lack such hardware is considerably lower. Yet another - problem is that many AES implementations are vulnerable to cache- - collision timing attacks ([Cache-Collisions]). - - This document provides a definition and implementation guide for - three algorithms: - - 1. The ChaCha20 cipher. This is a high-speed cipher first described - in [ChaCha]. It is considerably faster than AES in software-only - implementations, making it around three times as fast on - platforms that lack specialized AES hardware. See Appendix B for - some hard numbers. ChaCha20 is also not sensitive to timing - attacks (see the security considerations in Section 4). This - algorithm is described in Section 2.4 - - 2. The Poly1305 authenticator. This is a high-speed message - authentication code. Implementation is also straightforward and - easy to get right. The algorithm is described in Section 2.5. - - 3. The CHACHA20-POLY1305 Authenticated Encryption with Associated - Data (AEAD) construction, described in Section 2.8. - - This document and its predecessor do not introduce these new - algorithms for the first time. They have been defined in scientific - papers by D. J. Bernstein [ChaCha][Poly1305]. The purpose of this - document is to serve as a stable reference for IETF documents making - use of these algorithms. - - These algorithms have undergone rigorous analysis. Several papers - discuss the security of Salsa and ChaCha ([LatinDances], - [LatinDances2], [Zhenqing2012]). - - - -Nir & Langley Informational [Page 4] - -RFC 8439 ChaCha20 & Poly1305 June 2018 - - - This document represents the consensus of the Crypto Forum Research - Group (CFRG). It replaces [RFC7539]. - -1.1. Conventions Used in This Document - - The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", - "SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and - "OPTIONAL" in this document are to be interpreted as described in BCP - 14 [RFC2119] [RFC8174] when, and only when, they appear in all - capitals, as shown here. - - The description of the ChaCha algorithm will at various time refer to - the ChaCha state as a "vector" or as a "matrix". This follows the - use of these terms in [ChaCha]. The matrix notation is more visually - convenient and gives a better notion as to why some rounds are called - "column rounds" while others are called "diagonal rounds". Here's a - diagram of how the matrices relate to vectors (using the C language - convention of zero being the index origin). - - 0 1 2 3 - 4 5 6 7 - 8 9 10 11 - 12 13 14 15 - - The elements in this vector or matrix are 32-bit unsigned integers. - - The algorithm name is "ChaCha". "ChaCha20" is a specific instance - where 20 "rounds" (or 80 quarter rounds -- see Section 2.1) are used. - Other variations are defined, with 8 or 12 rounds, but in this - document we only describe the 20-round ChaCha, so the names "ChaCha" - and "ChaCha20" will be used interchangeably. - -2. The Algorithms - - The subsections below describe the algorithms used and the AEAD - construction. - -2.1. The ChaCha Quarter Round - - The basic operation of the ChaCha algorithm is the quarter round. It - operates on four 32-bit unsigned integers, denoted a, b, c, and d. - The operation is as follows (in C-like notation): - - a += b; d ^= a; d <<<= 16; - c += d; b ^= c; b <<<= 12; - a += b; d ^= a; d <<<= 8; - c += d; b ^= c; b <<<= 7; - - - - -Nir & Langley Informational [Page 5] - -RFC 8439 ChaCha20 & Poly1305 June 2018 - - - Where "+" denotes integer addition modulo 2^32, "^" denotes a bitwise - Exclusive OR (XOR), and "<<< n" denotes an n-bit left roll (towards - the high bits). - - For example, let's see the add, XOR, and roll operations from the - fourth line with sample numbers: - - a = 0x11111111 - b = 0x01020304 - c = 0x77777777 - d = 0x01234567 - c = c + d = 0x77777777 + 0x01234567 = 0x789abcde - b = b ^ c = 0x01020304 ^ 0x789abcde = 0x7998bfda - b = b <<< 7 = 0x7998bfda <<< 7 = 0xcc5fed3c - -2.1.1. Test Vector for the ChaCha Quarter Round - - For a test vector, we will use the same numbers as in the example, - adding something random for c. - - a = 0x11111111 - b = 0x01020304 - c = 0x9b8d6f43 - d = 0x01234567 - - After running a Quarter Round on these four numbers, we get these: - - a = 0xea2a92f4 - b = 0xcb1cf8ce - c = 0x4581472e - d = 0x5881c4bb - -2.2. A Quarter Round on the ChaCha State - - The ChaCha state does not have four integer numbers: it has 16. So - the quarter-round operation works on only four of them -- hence the - name. Each quarter round operates on four predetermined numbers in - the ChaCha state. We will denote by QUARTERROUND(x, y, z, w) a - quarter-round operation on the numbers at indices x, y, z, and w of - the ChaCha state when viewed as a vector. For example, if we apply - QUARTERROUND(1, 5, 9, 13) to a state, this means running the quarter- - round operation on the elements marked with an asterisk, while - leaving the others alone: - - 0 *a 2 3 - 4 *b 6 7 - 8 *c 10 11 - 12 *d 14 15 - - - -Nir & Langley Informational [Page 6] - -RFC 8439 ChaCha20 & Poly1305 June 2018 - - - Note that this run of quarter round is part of what is called a - "column round". - -2.2.1. Test Vector for the Quarter Round on the ChaCha State - - For a test vector, we will use a ChaCha state that was generated - randomly: - - Sample ChaCha State - - 879531e0 c5ecf37d 516461b1 c9a62f8a - 44c20ef3 3390af7f d9fc690b 2a5f714c - 53372767 b00a5631 974c541a 359e9963 - 5c971061 3d631689 2098d9d6 91dbd320 - - We will apply the QUARTERROUND(2, 7, 8, 13) operation to this state. - For obvious reasons, this one is part of what is called a "diagonal - round": - - After applying QUARTERROUND(2, 7, 8, 13) - - 879531e0 c5ecf37d *bdb886dc c9a62f8a - 44c20ef3 3390af7f d9fc690b *cfacafd2 - *e46bea80 b00a5631 974c541a 359e9963 - 5c971061 *ccc07c79 2098d9d6 91dbd320 - - Note that only the numbers in positions 2, 7, 8, and 13 changed. - -2.3. The ChaCha20 Block Function - - The ChaCha block function transforms a ChaCha state by running - multiple quarter rounds. - - The inputs to ChaCha20 are: - - o A 256-bit key, treated as a concatenation of eight 32-bit little- - endian integers. - - o A 96-bit nonce, treated as a concatenation of three 32-bit little- - endian integers. - - o A 32-bit block count parameter, treated as a 32-bit little-endian - integer. - - The output is 64 random-looking bytes. - - - - - - -Nir & Langley Informational [Page 7] - -RFC 8439 ChaCha20 & Poly1305 June 2018 - - - The ChaCha algorithm described here uses a 256-bit key. The original - algorithm also specified 128-bit keys and 8- and 12-round variants, - but these are out of scope for this document. In this section, we - describe the ChaCha block function. - - Note also that the original ChaCha had a 64-bit nonce and 64-bit - block count. We have modified this here to be more consistent with - recommendations in Section 3.2 of [RFC5116]. This limits the use of - a single (key,nonce) combination to 2^32 blocks, or 256 GB, but that - is enough for most uses. In cases where a single key is used by - multiple senders, it is important to make sure that they don't use - the same nonces. This can be assured by partitioning the nonce space - so that the first 32 bits are unique per sender, while the other 64 - bits come from a counter. - - The ChaCha20 state is initialized as follows: - - o The first four words (0-3) are constants: 0x61707865, 0x3320646e, - 0x79622d32, 0x6b206574. - - o The next eight words (4-11) are taken from the 256-bit key by - reading the bytes in little-endian order, in 4-byte chunks. - - o Word 12 is a block counter. Since each block is 64-byte, a 32-bit - word is enough for 256 gigabytes of data. - - o Words 13-15 are a nonce, which MUST not be repeated for the same - key. The 13th word is the first 32 bits of the input nonce taken - as a little-endian integer, while the 15th word is the last 32 - bits. - - cccccccc cccccccc cccccccc cccccccc - kkkkkkkk kkkkkkkk kkkkkkkk kkkkkkkk - kkkkkkkk kkkkkkkk kkkkkkkk kkkkkkkk - bbbbbbbb nnnnnnnn nnnnnnnn nnnnnnnn - - c=constant k=key b=blockcount n=nonce - - - - - - - - - - - - - - -Nir & Langley Informational [Page 8] - -RFC 8439 ChaCha20 & Poly1305 June 2018 - - - ChaCha20 runs 20 rounds, alternating between "column rounds" and - "diagonal rounds". Each round consists of four quarter-rounds, and - they are run as follows. Quarter rounds 1-4 are part of a "column" - round, while 5-8 are part of a "diagonal" round: - - QUARTERROUND(0, 4, 8, 12) - QUARTERROUND(1, 5, 9, 13) - QUARTERROUND(2, 6, 10, 14) - QUARTERROUND(3, 7, 11, 15) - QUARTERROUND(0, 5, 10, 15) - QUARTERROUND(1, 6, 11, 12) - QUARTERROUND(2, 7, 8, 13) - QUARTERROUND(3, 4, 9, 14) - - At the end of 20 rounds (or 10 iterations of the above list), we add - the original input words to the output words, and serialize the - result by sequencing the words one-by-one in little-endian order. - - Note: "addition" in the above paragraph is done modulo 2^32. In some - machine languages, this is called carryless addition on a 32-bit - word. - -2.3.1. The ChaCha20 Block Function in Pseudocode - - Note: This section and a few others contain pseudocode for the - algorithm explained in a previous section. Every effort was made for - the pseudocode to accurately reflect the algorithm as described in - the preceding section. If a conflict is still present, the textual - explanation and the test vectors are normative. - - inner_block (state): - Qround(state, 0, 4, 8, 12) - Qround(state, 1, 5, 9, 13) - Qround(state, 2, 6, 10, 14) - Qround(state, 3, 7, 11, 15) - Qround(state, 0, 5, 10, 15) - Qround(state, 1, 6, 11, 12) - Qround(state, 2, 7, 8, 13) - Qround(state, 3, 4, 9, 14) - end - - - - - - - - - - - -Nir & Langley Informational [Page 9] - -RFC 8439 ChaCha20 & Poly1305 June 2018 - - - chacha20_block(key, counter, nonce): - state = constants | key | counter | nonce - initial_state = state - for i=1 upto 10 - inner_block(state) - end - state += initial_state - return serialize(state) - end - - Where the pipe character ("|") denotes concatenation. - -2.3.2. Test Vector for the ChaCha20 Block Function - - For a test vector, we will use the following inputs to the ChaCha20 - block function: - - o Key = 00:01:02:03:04:05:06:07:08:09:0a:0b:0c:0d:0e:0f:10:11:12:13: - 14:15:16:17:18:19:1a:1b:1c:1d:1e:1f. The key is a sequence of - octets with no particular structure before we copy it into the - ChaCha state. - - o Nonce = (00:00:00:09:00:00:00:4a:00:00:00:00) - - o Block Count = 1. - - After setting up the ChaCha state, it looks like this: - - ChaCha state with the key setup. - - 61707865 3320646e 79622d32 6b206574 - 03020100 07060504 0b0a0908 0f0e0d0c - 13121110 17161514 1b1a1918 1f1e1d1c - 00000001 09000000 4a000000 00000000 - - After running 20 rounds (10 column rounds interleaved with 10 - "diagonal rounds"), the ChaCha state looks like this: - - ChaCha state after 20 rounds - - 837778ab e238d763 a67ae21e 5950bb2f - c4f2d0c7 fc62bb2f 8fa018fc 3f5ec7b7 - 335271c2 f29489f3 eabda8fc 82e46ebd - d19c12b4 b04e16de 9e83d0cb 4e3c50a2 - - Finally, we add the original state to the result (simple vector or - matrix addition), giving this: - - - - -Nir & Langley Informational [Page 10] - -RFC 8439 ChaCha20 & Poly1305 June 2018 - - - ChaCha state at the end of the ChaCha20 operation - - e4e7f110 15593bd1 1fdd0f50 c47120a3 - c7f4d1c7 0368c033 9aaa2204 4e6cd4c3 - 466482d2 09aa9f07 05d7c214 a2028bd9 - d19c12b5 b94e16de e883d0cb 4e3c50a2 - - After we serialize the state, we get this: - - Serialized Block: - 000 10 f1 e7 e4 d1 3b 59 15 50 0f dd 1f a3 20 71 c4 .....;Y.P.... q. - 016 c7 d1 f4 c7 33 c0 68 03 04 22 aa 9a c3 d4 6c 4e ....3.h.."....lN - 032 d2 82 64 46 07 9f aa 09 14 c2 d7 05 d9 8b 02 a2 ..dF............ - 048 b5 12 9c d1 de 16 4e b9 cb d0 83 e8 a2 50 3c 4e ......N......P.S. - - Poly1305 r = 455e9a4057ab6080f47b42c052bac7b - Poly1305 s = ff53d53e7875932aebd9751073d6e10a - - keystream bytes: - 9f:7b:e9:5d:01:fd:40:ba:15:e2:8f:fb:36:81:0a:ae: - c1:c0:88:3f:09:01:6e:de:dd:8a:d0:87:55:82:03:a5: - 4e:9e:cb:38:ac:8e:5e:2b:b8:da:b2:0f:fa:db:52:e8: - 75:04:b2:6e:be:69:6d:4f:60:a4:85:cf:11:b8:1b:59: - fc:b1:c4:5f:42:19:ee:ac:ec:6a:de:c3:4e:66:69:78: - 8e:db:41:c4:9c:a3:01:e1:27:e0:ac:ab:3b:44:b9:cf: - 5c:86:bb:95:e0:6b:0d:f2:90:1a:b6:45:e4:ab:e6:22: - 15:38 - - Ciphertext: - 000 d3 1a 8d 34 64 8e 60 db 7b 86 af bc 53 ef 7e c2 ...4d.`.{...S.~. - 016 a4 ad ed 51 29 6e 08 fe a9 e2 b5 a7 36 ee 62 d6 ...Q)n......6.b. - 032 3d be a4 5e 8c a9 67 12 82 fa fb 69 da 92 72 8b =..^..g....i..r. - 048 1a 71 de 0a 9e 06 0b 29 05 d6 a5 b6 7e cd 3b 36 .q.....)....~.;6 - 064 92 dd bd 7f 2d 77 8b 8c 98 03 ae e3 28 09 1b 58 ....-w......(..X - 080 fa b3 24 e4 fa d6 75 94 55 85 80 8b 48 31 d7 bc ..$...u.U...H1.. - 096 3f f4 de f0 8e 4b 7a 9d e5 76 d2 65 86 ce c6 4b ?....Kz..v.e...K - 112 61 16 a. - - - - - - - - - - - - - -Nir & Langley Informational [Page 24] - -RFC 8439 ChaCha20 & Poly1305 June 2018 - - - AEAD Construction for Poly1305: - 000 50 51 52 53 c0 c1 c2 c3 c4 c5 c6 c7 00 00 00 00 PQRS............ - 016 d3 1a 8d 34 64 8e 60 db 7b 86 af bc 53 ef 7e c2 ...4d.`.{...S.~. - 032 a4 ad ed 51 29 6e 08 fe a9 e2 b5 a7 36 ee 62 d6 ...Q)n......6.b. - 048 3d be a4 5e 8c a9 67 12 82 fa fb 69 da 92 72 8b =..^..g....i..r. - 064 1a 71 de 0a 9e 06 0b 29 05 d6 a5 b6 7e cd 3b 36 .q.....)....~.;6 - 080 92 dd bd 7f 2d 77 8b 8c 98 03 ae e3 28 09 1b 58 ....-w......(..X - 096 fa b3 24 e4 fa d6 75 94 55 85 80 8b 48 31 d7 bc ..$...u.U...H1.. - 112 3f f4 de f0 8e 4b 7a 9d e5 76 d2 65 86 ce c6 4b ?....Kz..v.e...K - 128 61 16 00 00 00 00 00 00 00 00 00 00 00 00 00 00 a............... - 144 0c 00 00 00 00 00 00 00 72 00 00 00 00 00 00 00 ........r....... - - Note the four zero bytes in line 000 and the 14 zero bytes in line - 128 - - Tag: - 1a:e1:0b:59:4f:09:e2:6a:7e:90:2e:cb:d0:60:06:91 - -3. Implementation Advice - - Each block of ChaCha20 involves 16 move operations and one increment - operation for loading the state, 80 each of XOR, addition and roll - operations for the rounds, 16 more add operations and 16 XOR - operations for protecting the plaintext. Section 2.3 describes the - ChaCha block function as "adding the original input words". This - implies that before starting the rounds on the ChaCha state, we copy - it aside, only to add it in later. This is correct, but we can save - a few operations if we instead copy the state and do the work on the - copy. This way, for the next block you don't need to recreate the - state, but only to increment the block counter. This saves - approximately 5.5% of the cycles. - - It is not recommended to use a generic big number library such as the - one in OpenSSL for the arithmetic operations in Poly1305. Such - libraries use dynamic allocation to be able to handle an integer of - any size, but that flexibility comes at the expense of performance as - well as side-channel security. More efficient implementations that - run in constant time are available, one of them in D. J. Bernstein's - own library, NaCl ([NaCl]). A constant-time but not optimal approach - would be to naively implement the arithmetic operations for 288-bit - integers, because even a naive implementation will not exceed 2^288 - in the multiplication of (acc+block) and r. An efficient constant- - time implementation can be found in the public domain library - poly1305-donna ([Poly1305_Donna]). - - - - - - - -Nir & Langley Informational [Page 25] - -RFC 8439 ChaCha20 & Poly1305 June 2018 - - -4. Security Considerations - - The ChaCha20 cipher is designed to provide 256-bit security. - - The Poly1305 authenticator is designed to ensure that forged messages - are rejected with a probability of 1-(n/(2^102)) for a 16n-byte - message, even after sending 2^64 legitimate messages, so it is - SUF-CMA (strong unforgeability against chosen-message attacks) in the - terminology of [AE]. - - Proving the security of either of these is beyond the scope of this - document. Such proofs are available in the referenced academic - papers ([ChaCha], [Poly1305], [LatinDances], [LatinDances2], and - [Zhenqing2012]). - - The most important security consideration in implementing this - document is the uniqueness of the nonce used in ChaCha20. Counters - and LFSRs are both acceptable ways of generating unique nonces, as is - encrypting a counter using a block cipher with a 64-bit block size - such as DES. Note that it is not acceptable to use a truncation of a - counter encrypted with block ciphers with 128-bit or 256-bit blocks, - because such a truncation may repeat after a short time. - - Consequences of repeating a nonce: If a nonce is repeated, then both - the one-time Poly1305 key and the keystream are identical between the - messages. This reveals the XOR of the plaintexts, because the XOR of - the plaintexts is equal to the XOR of the ciphertexts. - - The Poly1305 key MUST be unpredictable to an attacker. Randomly - generating the key would fulfill this requirement, except that - Poly1305 is often used in communications protocols, so the receiver - should know the key. Pseudorandom number generation such as by - encrypting a counter is acceptable. Using ChaCha with a secret key - and a nonce is also acceptable. - - The algorithms presented here were designed to be easy to implement - in constant time to avoid side-channel vulnerabilities. The - operations used in ChaCha20 are all additions, XORs, and fixed rolls. - All of these can and should be implemented in constant time. Access - to offsets into the ChaCha state and the number of operations do not - depend on any property of the key, eliminating the chance of - information about the key leaking through the timing of cache misses. - - For Poly1305, the operations are addition, multiplication. and - modulus, all on numbers with greater than 128 bits. This can be done - in constant time, but a naive implementation (such as using some - generic big number library) will not be constant time. For example, - if the multiplication is performed as a separate operation from the - - - -Nir & Langley Informational [Page 26] - -RFC 8439 ChaCha20 & Poly1305 June 2018 - - - modulus, the result will sometimes be under 2^256 and sometimes be - above 2^256. Implementers should be careful about timing side- - channels for Poly1305 by using the appropriate implementation of - these operations. - - Validating the authenticity of a message involves a bitwise - comparison of the calculated tag with the received tag. In most use - cases, nonces and AAD contents are not "used up" until a valid - message is received. This allows an attacker to send multiple - identical messages with different tags until one passes the tag - comparison. This is hard if the attacker has to try all 2^128 - possible tags one by one. However, if the timing of the tag - comparison operation reveals how long a prefix of the calculated and - received tags is identical, the number of messages can be reduced - significantly. For this reason, with online protocols, - implementation MUST use a constant-time comparison function rather - than relying on optimized but insecure library functions such as the - C language's memcmp(). - - Additionally, any protocol using this algorithm MUST include the - complete tag to minimize the opportunity for forgery. Tag truncation - MUST NOT be done. - -5. IANA Considerations - - IANA has updated the entry in the "Authenticated Encryption with - Associated Data (AEAD) Parameters" registry with 29 as the Numeric ID - and "AEAD_CHACHA20_POLY1305" as the name to point to this document as - its reference. - -6. References - -6.1. Normative References - - [ChaCha] Bernstein, D., "ChaCha, a variant of Salsa20", January - 2008, . - - [Poly1305] - Bernstein, D., "The Poly1305-AES message-authentication - code", March 2005, - . - - [RFC2119] Bradner, S., "Key words for use in RFCs to Indicate - Requirement Levels", BCP 14, RFC 2119, - DOI 10.17487/RFC2119, March 1997, - . - - - - - -Nir & Langley Informational [Page 27] - -RFC 8439 ChaCha20 & Poly1305 June 2018 - - - [RFC8174] Leiba, B., "Ambiguity of Uppercase vs Lowercase in RFC - 2119 Key Words", BCP 14, RFC 8174, DOI 10.17487/RFC8174, - May 2017, . - -6.2. Informative References - - [AE] Bellare, M. and C. Namprempre, "Authenticated Encryption: - Relations among notions and analysis of the generic - composition paradigm", DOI 10.1007/s00145-008-9026-x, - September 2008, - . - - [Cache-Collisions] - Bonneau, J. and I. Mironov, "Cache-Collision Timing - Attacks Against AES", 2006, - . - - [FIPS-197] - National Institute of Standards and Technology, "Advanced - Encryption Standard (AES)", FIPS PUB 197, November 2001, - . - - [LatinDances] - Aumasson, J., Fischer, S., Khazaei, S., Meier, W., and C. - Rechberger, "New Features of Latin Dances: Analysis of - Salsa, ChaCha, and Rumba", December 2007, - . - - [LatinDances2] - Ishiguro, T., Kiyomoto, S., and Y. Miyake, "Modified - version of 'Latin Dances Revisited: New Analytic Results - of Salsa20 and ChaCha'", February 2012, - . - - [NaCl] Bernstein, D., Lange, T., and P. Schwabe, "NaCl: - Networking and Cryptography library", July 2012, - . - - [Poly1305_Donna] - "poly1305-donna", commit e6ad6e0, March 2016, - . - - [Procter] Procter, G., "A Security Analysis of the Composition of - ChaCha20 and Poly1305", August 2014, - . - - - - - -Nir & Langley Informational [Page 28] - -RFC 8439 ChaCha20 & Poly1305 June 2018 - - - [RFC5116] McGrew, D., "An Interface and Algorithms for Authenticated - Encryption", RFC 5116, DOI 10.17487/RFC5116, January 2008, - . - - [RFC7296] Kaufman, C., Hoffman, P., Nir, Y., Eronen, P., and T. - Kivinen, "Internet Key Exchange Protocol Version 2 - (IKEv2)", STD 79, RFC 7296, DOI 10.17487/RFC7296, October - 2014, . - - [RFC7539] Nir, Y. and A. Langley, "ChaCha20 and Poly1305 for IETF - Protocols", RFC 7539, DOI 10.17487/RFC7539, May 2015, - . - - [SP800-67] - National Institute of Standards and Technology, - "Recommendation for the Triple Data Encryption Algorithm - (TDEA) Block Cipher", NIST 800-67, Rev. 2, November 2017, - . - - [Standby-Cipher] - McGrew, D., Grieco, A., and Y. Sheffer, "Selection of - Future Cryptographic Standards", Work in Progress, draft- - mcgrew-standby-cipher-00, January 2013. - - [Zhenqing2012] - Zhenqing, S., Bin, Z., Dengguo, F., and W. Wenling, - "Improved Key Recovery Attacks on Reduced-Round Salsa20 - and ChaCha*", 2012. - - - - - - - - - - - - - - - - - - - - - - -Nir & Langley Informational [Page 29] - -RFC 8439 ChaCha20 & Poly1305 June 2018 - - -Appendix A. Additional Test Vectors - - The subsections of this appendix contain more test vectors for the - algorithms in the subsections of Section 2. - -A.1. The ChaCha20 Block Functions - - Test Vector #1: - ============== - - Key: - 000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ - 016 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ - - Nonce: - 000 00 00 00 00 00 00 00 00 00 00 00 00 ............ - - Block Counter = 0 - - ChaCha state at the end - ade0b876 903df1a0 e56a5d40 28bd8653 - b819d2bd 1aed8da0 ccef36a8 c70d778b - 7c5941da 8d485751 3fe02477 374ad8b8 - f4b8436a 1ca11815 69b687c3 8665eeb2 - - Keystream: - 000 76 b8 e0 ad a0 f1 3d 90 40 5d 6a e5 53 86 bd 28 v.....=.@]j.S..( - 016 bd d2 19 b8 a0 8d ed 1a a8 36 ef cc 8b 77 0d c7 .........6...w.. - 032 da 41 59 7c 51 57 48 8d 77 24 e0 3f b8 d8 4a 37 .AY|QWH.w$.?..J7 - 048 6a 43 b8 f4 15 18 a1 1c c3 87 b6 69 b2 ee 65 86 jC.........i..e. - - Test Vector #2: - ============== - - Key: - 000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ - 016 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ - - Nonce: - 000 00 00 00 00 00 00 00 00 00 00 00 00 ............ - - Block Counter = 1 - - ChaCha state at the end - bee7079f 7a385155 7c97ba98 0d082d73 - a0290fcb 6965e348 3e53c612 ed7aee32 - 7621b729 434ee69c b03371d5 d539d874 - 281fed31 45fb0a51 1f0ae1ac 6f4d794b - - - -Nir & Langley Informational [Page 30] - -RFC 8439 ChaCha20 & Poly1305 June 2018 - - - Keystream: - 000 9f 07 e7 be 55 51 38 7a 98 ba 97 7c 73 2d 08 0d ....UQ8z...|s-.. - 016 cb 0f 29 a0 48 e3 65 69 12 c6 53 3e 32 ee 7a ed ..).H.ei..S>2.z. - 032 29 b7 21 76 9c e6 4e 43 d5 71 33 b0 74 d8 39 d5 ).!v..NC.q3.t.9. - 048 31 ed 1f 28 51 0a fb 45 ac e1 0a 1f 4b 79 4d 6f 1..(Q..E....KyMo - - Test Vector #3: - ============== - - Key: - 000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ - 016 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 ................ - - Nonce: - 000 00 00 00 00 00 00 00 00 00 00 00 00 ............ - - Block Counter = 1 - - ChaCha state at the end - 2452eb3a 9249f8ec 8d829d9b ddd4ceb1 - e8252083 60818b01 f38422b8 5aaa49c9 - bb00ca8e da3ba7b4 c4b592d1 fdf2732f - 4436274e 2561b3c8 ebdd4aa6 a0136c00 - - Keystream: - 000 3a eb 52 24 ec f8 49 92 9b 9d 82 8d b1 ce d4 dd :.R$..I......... - 016 83 20 25 e8 01 8b 81 60 b8 22 84 f3 c9 49 aa 5a . %....`."...I.Z - 032 8e ca 00 bb b4 a7 3b da d1 92 b5 c4 2f 73 f2 fd ......;...../s.. - 048 4e 27 36 44 c8 b3 61 25 a6 4a dd eb 00 6c 13 a0 N'6D..a%.J...l.. - - Test Vector #4: - ============== - - Key: - 000 00 ff 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ - 016 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ - - Nonce: - 000 00 00 00 00 00 00 00 00 00 00 00 00 ............ - - Block Counter = 2 - - ChaCha state at the end - fb4dd572 4bc42ef1 df922636 327f1394 - a78dea8f 5e269039 a1bebbc1 caf09aae - a25ab213 48a6b46c 1b9d9bcb 092c5be6 - 546ca624 1bec45d5 87f47473 96f0992e - - - - -Nir & Langley Informational [Page 31] - -RFC 8439 ChaCha20 & Poly1305 June 2018 - - - Keystream: - 000 72 d5 4d fb f1 2e c4 4b 36 26 92 df 94 13 7f 32 r.M....K6&.....2 - 016 8f ea 8d a7 39 90 26 5e c1 bb be a1 ae 9a f0 ca ....9.&^........ - 032 13 b2 5a a2 6c b4 a6 48 cb 9b 9d 1b e6 5b 2c 09 ..Z.l..H.....[,. - 048 24 a6 6c 54 d5 45 ec 1b 73 74 f4 87 2e 99 f0 96 $.lT.E..st...... - - Test Vector #5: - ============== - - Key: - 000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ - 016 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ - - Nonce: - 000 00 00 00 00 00 00 00 00 00 00 00 02 ............ - - Block Counter = 0 - - ChaCha state at the end - 374dc6c2 3736d58c b904e24a cd3f93ef - 88228b1a 96a4dfb3 5b76ab72 c727ee54 - 0e0e978a f3145c95 1b748ea8 f786c297 - 99c28f5f 628314e8 398a19fa 6ded1b53 - - Keystream: - 000 c2 c6 4d 37 8c d5 36 37 4a e2 04 b9 ef 93 3f cd ..M7..67J.....?. - 016 1a 8b 22 88 b3 df a4 96 72 ab 76 5b 54 ee 27 c7 ..".....r.v[T.'. - 032 8a 97 0e 0e 95 5c 14 f3 a8 8e 74 1b 97 c2 86 f7 .....\....t..... - 048 5f 8f c2 99 e8 14 83 62 fa 19 8a 39 53 1b ed 6d _......b...9S..m - - - - - - - - - - - - - - - - - - - - - - -Nir & Langley Informational [Page 32] - -RFC 8439 ChaCha20 & Poly1305 June 2018 - - -A.2. ChaCha20 Encryption - - Test Vector #1: - ============== - - Key: - 000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ - 016 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ - - Nonce: - 000 00 00 00 00 00 00 00 00 00 00 00 00 ............ - - Initial Block Counter = 0 - - Plaintext: - 000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ - 016 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ - 032 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ - 048 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ - - Ciphertext: - 000 76 b8 e0 ad a0 f1 3d 90 40 5d 6a e5 53 86 bd 28 v.....=.@]j.S..( - 016 bd d2 19 b8 a0 8d ed 1a a8 36 ef cc 8b 77 0d c7 .........6...w.. - 032 da 41 59 7c 51 57 48 8d 77 24 e0 3f b8 d8 4a 37 .AY|QWH.w$.?..J7 - 048 6a 43 b8 f4 15 18 a1 1c c3 87 b6 69 b2 ee 65 86 jC.........i..e. - - Test Vector #2: - ============== - - Key: - 000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ - 016 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 ................ - - Nonce: - 000 00 00 00 00 00 00 00 00 00 00 00 02 ............ - - Initial Block Counter = 1 - - - - - - - - - - - - - - -Nir & Langley Informational [Page 33] - -RFC 8439 ChaCha20 & Poly1305 June 2018 - - - Plaintext: - 000 41 6e 79 20 73 75 62 6d 69 73 73 69 6f 6e 20 74 Any submission t - 016 6f 20 74 68 65 20 49 45 54 46 20 69 6e 74 65 6e o the IETF inten - 032 64 65 64 20 62 79 20 74 68 65 20 43 6f 6e 74 72 ded by the Contr - 048 69 62 75 74 6f 72 20 66 6f 72 20 70 75 62 6c 69 ibutor for publi - 064 63 61 74 69 6f 6e 20 61 73 20 61 6c 6c 20 6f 72 cation as all or - 080 20 70 61 72 74 20 6f 66 20 61 6e 20 49 45 54 46 part of an IETF - 096 20 49 6e 74 65 72 6e 65 74 2d 44 72 61 66 74 20 Internet-Draft - 112 6f 72 20 52 46 43 20 61 6e 64 20 61 6e 79 20 73 or RFC and any s - 128 74 61 74 65 6d 65 6e 74 20 6d 61 64 65 20 77 69 tatement made wi - 144 74 68 69 6e 20 74 68 65 20 63 6f 6e 74 65 78 74 thin the context - 160 20 6f 66 20 61 6e 20 49 45 54 46 20 61 63 74 69 of an IETF acti - 176 76 69 74 79 20 69 73 20 63 6f 6e 73 69 64 65 72 vity is consider - 192 65 64 20 61 6e 20 22 49 45 54 46 20 43 6f 6e 74 ed an "IETF Cont - 208 72 69 62 75 74 69 6f 6e 22 2e 20 53 75 63 68 20 ribution". Such - 224 73 74 61 74 65 6d 65 6e 74 73 20 69 6e 63 6c 75 statements inclu - 240 64 65 20 6f 72 61 6c 20 73 74 61 74 65 6d 65 6e de oral statemen - 256 74 73 20 69 6e 20 49 45 54 46 20 73 65 73 73 69 ts in IETF sessi - 272 6f 6e 73 2c 20 61 73 20 77 65 6c 6c 20 61 73 20 ons, as well as - 288 77 72 69 74 74 65 6e 20 61 6e 64 20 65 6c 65 63 written and elec - 304 74 72 6f 6e 69 63 20 63 6f 6d 6d 75 6e 69 63 61 tronic communica - 320 74 69 6f 6e 73 20 6d 61 64 65 20 61 74 20 61 6e tions made at an - 336 79 20 74 69 6d 65 20 6f 72 20 70 6c 61 63 65 2c y time or place, - 352 20 77 68 69 63 68 20 61 72 65 20 61 64 64 72 65 which are addre - 368 73 73 65 64 20 74 6f ssed to - - - - - - - - - - - - - - - - - - - - - - - - - - -Nir & Langley Informational [Page 34] - -RFC 8439 ChaCha20 & Poly1305 June 2018 - - - Ciphertext: - 000 a3 fb f0 7d f3 fa 2f de 4f 37 6c a2 3e 82 73 70 ...}../.O7l.>.sp - 016 41 60 5d 9f 4f 4f 57 bd 8c ff 2c 1d 4b 79 55 ec A`].OOW...,.KyU. - 032 2a 97 94 8b d3 72 29 15 c8 f3 d3 37 f7 d3 70 05 *....r)....7..p. - 048 0e 9e 96 d6 47 b7 c3 9f 56 e0 31 ca 5e b6 25 0d ....G...V.1.^.%. - 064 40 42 e0 27 85 ec ec fa 4b 4b b5 e8 ea d0 44 0e @B.'....KK....D. - 080 20 b6 e8 db 09 d8 81 a7 c6 13 2f 42 0e 52 79 50 ........./B.RyP - 096 42 bd fa 77 73 d8 a9 05 14 47 b3 29 1c e1 41 1c B..ws....G.)..A. - 112 68 04 65 55 2a a6 c4 05 b7 76 4d 5e 87 be a8 5a h.eU*....vM^...Z - 128 d0 0f 84 49 ed 8f 72 d0 d6 62 ab 05 26 91 ca 66 ...I..r..b..&..f - 144 42 4b c8 6d 2d f8 0e a4 1f 43 ab f9 37 d3 25 9d BK.m-....C..7.%. - 160 c4 b2 d0 df b4 8a 6c 91 39 dd d7 f7 69 66 e9 28 ......l.9...if.( - 176 e6 35 55 3b a7 6c 5c 87 9d 7b 35 d4 9e b2 e6 2b .5U;.l\..{5....+ - 192 08 71 cd ac 63 89 39 e2 5e 8a 1e 0e f9 d5 28 0f .q..c.9.^.....(. - 208 a8 ca 32 8b 35 1c 3c 76 59 89 cb cf 3d aa 8b 6c ..2.5.vC.. - 080 1a 55 32 05 57 16 ea d6 96 25 68 f8 7d 3f 3f 77 .U2.W....%h.}??w - 096 04 c6 a8 d1 bc d1 bf 4d 50 d6 15 4b 6d a7 31 b1 .......MP..Km.1. - 112 87 b5 8d fd 72 8a fa 36 75 7a 79 7a c1 88 d1 ....r..6uzyz... - -A.3. Poly1305 Message Authentication Code - - Notice how, in test vector #2, r is equal to zero. The part of the - Poly1305 algorithm where the accumulator is multiplied by r means - that with r equal zero, the tag will be equal to s regardless of the - content of the text. Fortunately, all the proposed methods of - generating r are such that getting this particular weak key is very - unlikely. - - Test Vector #1: - ============== - - One-time Poly1305 Key: - 000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ - 016 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ - - Text to MAC: - 000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ - 016 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ - 032 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ - 048 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ - - Tag: - 000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ - - Test Vector #2: - ============== - - One-time Poly1305 Key: - 000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ - 016 36 e5 f6 b5 c5 e0 60 70 f0 ef ca 96 22 7a 86 3e 6.....`p...."z.> - - - - - - - - - - -Nir & Langley Informational [Page 36] - -RFC 8439 ChaCha20 & Poly1305 June 2018 - - - Text to MAC: - 000 41 6e 79 20 73 75 62 6d 69 73 73 69 6f 6e 20 74 Any submission t - 016 6f 20 74 68 65 20 49 45 54 46 20 69 6e 74 65 6e o the IETF inten - 032 64 65 64 20 62 79 20 74 68 65 20 43 6f 6e 74 72 ded by the Contr - 048 69 62 75 74 6f 72 20 66 6f 72 20 70 75 62 6c 69 ibutor for publi - 064 63 61 74 69 6f 6e 20 61 73 20 61 6c 6c 20 6f 72 cation as all or - 080 20 70 61 72 74 20 6f 66 20 61 6e 20 49 45 54 46 part of an IETF - 096 20 49 6e 74 65 72 6e 65 74 2d 44 72 61 66 74 20 Internet-Draft - 112 6f 72 20 52 46 43 20 61 6e 64 20 61 6e 79 20 73 or RFC and any s - 128 74 61 74 65 6d 65 6e 74 20 6d 61 64 65 20 77 69 tatement made wi - 144 74 68 69 6e 20 74 68 65 20 63 6f 6e 74 65 78 74 thin the context - 160 20 6f 66 20 61 6e 20 49 45 54 46 20 61 63 74 69 of an IETF acti - 176 76 69 74 79 20 69 73 20 63 6f 6e 73 69 64 65 72 vity is consider - 192 65 64 20 61 6e 20 22 49 45 54 46 20 43 6f 6e 74 ed an "IETF Cont - 208 72 69 62 75 74 69 6f 6e 22 2e 20 53 75 63 68 20 ribution". Such - 224 73 74 61 74 65 6d 65 6e 74 73 20 69 6e 63 6c 75 statements inclu - 240 64 65 20 6f 72 61 6c 20 73 74 61 74 65 6d 65 6e de oral statemen - 256 74 73 20 69 6e 20 49 45 54 46 20 73 65 73 73 69 ts in IETF sessi - 272 6f 6e 73 2c 20 61 73 20 77 65 6c 6c 20 61 73 20 ons, as well as - 288 77 72 69 74 74 65 6e 20 61 6e 64 20 65 6c 65 63 written and elec - 304 74 72 6f 6e 69 63 20 63 6f 6d 6d 75 6e 69 63 61 tronic communica - 320 74 69 6f 6e 73 20 6d 61 64 65 20 61 74 20 61 6e tions made at an - 336 79 20 74 69 6d 65 20 6f 72 20 70 6c 61 63 65 2c y time or place, - 352 20 77 68 69 63 68 20 61 72 65 20 61 64 64 72 65 which are addre - 368 73 73 65 64 20 74 6f ssed to - - Tag: - 000 36 e5 f6 b5 c5 e0 60 70 f0 ef ca 96 22 7a 86 3e 6.....`p...."z.> - - Test Vector #3: - ============== - - One-time Poly1305 Key: - 000 36 e5 f6 b5 c5 e0 60 70 f0 ef ca 96 22 7a 86 3e 6.....`p...."z.> - 016 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ - - - - - - - - - - - - - - - - -Nir & Langley Informational [Page 37] - -RFC 8439 ChaCha20 & Poly1305 June 2018 - - - Text to MAC: - 000 41 6e 79 20 73 75 62 6d 69 73 73 69 6f 6e 20 74 Any submission t - 016 6f 20 74 68 65 20 49 45 54 46 20 69 6e 74 65 6e o the IETF inten - 032 64 65 64 20 62 79 20 74 68 65 20 43 6f 6e 74 72 ded by the Contr - 048 69 62 75 74 6f 72 20 66 6f 72 20 70 75 62 6c 69 ibutor for publi - 064 63 61 74 69 6f 6e 20 61 73 20 61 6c 6c 20 6f 72 cation as all or - 080 20 70 61 72 74 20 6f 66 20 61 6e 20 49 45 54 46 part of an IETF - 096 20 49 6e 74 65 72 6e 65 74 2d 44 72 61 66 74 20 Internet-Draft - 112 6f 72 20 52 46 43 20 61 6e 64 20 61 6e 79 20 73 or RFC and any s - 128 74 61 74 65 6d 65 6e 74 20 6d 61 64 65 20 77 69 tatement made wi - 144 74 68 69 6e 20 74 68 65 20 63 6f 6e 74 65 78 74 thin the context - 160 20 6f 66 20 61 6e 20 49 45 54 46 20 61 63 74 69 of an IETF acti - 176 76 69 74 79 20 69 73 20 63 6f 6e 73 69 64 65 72 vity is consider - 192 65 64 20 61 6e 20 22 49 45 54 46 20 43 6f 6e 74 ed an "IETF Cont - 208 72 69 62 75 74 69 6f 6e 22 2e 20 53 75 63 68 20 ribution". Such - 224 73 74 61 74 65 6d 65 6e 74 73 20 69 6e 63 6c 75 statements inclu - 240 64 65 20 6f 72 61 6c 20 73 74 61 74 65 6d 65 6e de oral statemen - 256 74 73 20 69 6e 20 49 45 54 46 20 73 65 73 73 69 ts in IETF sessi - 272 6f 6e 73 2c 20 61 73 20 77 65 6c 6c 20 61 73 20 ons, as well as - 288 77 72 69 74 74 65 6e 20 61 6e 64 20 65 6c 65 63 written and elec - 304 74 72 6f 6e 69 63 20 63 6f 6d 6d 75 6e 69 63 61 tronic communica - 320 74 69 6f 6e 73 20 6d 61 64 65 20 61 74 20 61 6e tions made at an - 336 79 20 74 69 6d 65 20 6f 72 20 70 6c 61 63 65 2c y time or place, - 352 20 77 68 69 63 68 20 61 72 65 20 61 64 64 72 65 which are addre - 368 73 73 65 64 20 74 6f ssed to - - Tag: - 000 f3 47 7e 7c d9 54 17 af 89 a6 b8 79 4c 31 0c f0 .G~|.T.....yL1.. - - - - - - - - - - - - - - - - - - - - - - - -Nir & Langley Informational [Page 38] - -RFC 8439 ChaCha20 & Poly1305 June 2018 - - - Test Vector #4: - ============== - - One-time Poly1305 Key: - 000 1c 92 40 a5 eb 55 d3 8a f3 33 88 86 04 f6 b5 f0 ..@..U...3...... - 016 47 39 17 c1 40 2b 80 09 9d ca 5c bc 20 70 75 c0 G9..@+....\. pu. - - Text to MAC: - 000 27 54 77 61 73 20 62 72 69 6c 6c 69 67 2c 20 61 'Twas brillig, a - 016 6e 64 20 74 68 65 20 73 6c 69 74 68 79 20 74 6f nd the slithy to - 032 76 65 73 0a 44 69 64 20 67 79 72 65 20 61 6e 64 ves.Did gyre and - 048 20 67 69 6d 62 6c 65 20 69 6e 20 74 68 65 20 77 gimble in the w - 064 61 62 65 3a 0a 41 6c 6c 20 6d 69 6d 73 79 20 77 abe:.All mimsy w - 080 65 72 65 20 74 68 65 20 62 6f 72 6f 67 6f 76 65 ere the borogove - 096 73 2c 0a 41 6e 64 20 74 68 65 20 6d 6f 6d 65 20 s,.And the mome - 112 72 61 74 68 73 20 6f 75 74 67 72 61 62 65 2e raths outgrabe. - - Tag: - 000 45 41 66 9a 7e aa ee 61 e7 08 dc 7c bc c5 eb 62 EAf.~..a...|...b - - Test Vector #5: If one uses 130-bit partial reduction, does the code - handle the case where partially reduced final result is not fully - reduced? - - R: - 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 - S: - 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 - data: - FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF - tag: - 03 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 - - Test Vector #6: What happens if addition of s overflows modulo 2^128? - - R: - 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 - S: - FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF - data: - 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 - tag: - 03 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 - - - - - - - - -Nir & Langley Informational [Page 39] - -RFC 8439 ChaCha20 & Poly1305 June 2018 - - - Test Vector #7: What happens if data limb is all ones and there is - carry from lower limb? - - R: - 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 - S: - 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 - data: - FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF - F0 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF - 11 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 - tag: - 05 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 - - Test Vector #8: What happens if final result from polynomial part is - exactly 2^130-5? - - R: - 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 - S: - 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 - data: - FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF - FB FE FE FE FE FE FE FE FE FE FE FE FE FE FE FE - 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 - tag: - 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 - - Test Vector #9: What happens if final result from polynomial part is - exactly 2^130-6? - - R: - 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 - S: - 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 - data: - FD FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF - tag: - FA FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF - - - - - - - - - - - - -Nir & Langley Informational [Page 40] - -RFC 8439 ChaCha20 & Poly1305 June 2018 - - - Test Vector #10: What happens if 5*H+L-type reduction produces - 131-bit intermediate result? - - R: - 01 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 - S: - 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 - data: - E3 35 94 D7 50 5E 43 B9 00 00 00 00 00 00 00 00 - 33 94 D7 50 5E 43 79 CD 01 00 00 00 00 00 00 00 - 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 - 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 - tag: - 14 00 00 00 00 00 00 00 55 00 00 00 00 00 00 00 - - Test Vector #11: What happens if 5*H+L-type reduction produces - 131-bit final result? - - R: - 01 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 - S: - 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 - data: - E3 35 94 D7 50 5E 43 B9 00 00 00 00 00 00 00 00 - 33 94 D7 50 5E 43 79 CD 01 00 00 00 00 00 00 00 - 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 - tag: - 13 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 - -A.4. Poly1305 Key Generation Using ChaCha20 - - Test Vector #1: - ============== - - The ChaCha20 Key: - 000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ - 016 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ - - The nonce: - 000 00 00 00 00 00 00 00 00 00 00 00 00 ............ - - Poly1305 one-time key: - 000 76 b8 e0 ad a0 f1 3d 90 40 5d 6a e5 53 86 bd 28 v.....=.@]j.S..( - 016 bd d2 19 b8 a0 8d ed 1a a8 36 ef cc 8b 77 0d c7 .........6...w.. - - - - - - - -Nir & Langley Informational [Page 41] - -RFC 8439 ChaCha20 & Poly1305 June 2018 - - - Test Vector #2: - ============== - - The ChaCha20 Key - 000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ - 016 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 ................ - - The nonce: - 000 00 00 00 00 00 00 00 00 00 00 00 02 ............ - - Poly1305 one-time key: - 000 ec fa 25 4f 84 5f 64 74 73 d3 cb 14 0d a9 e8 76 ..%O._dts......v - 016 06 cb 33 06 6c 44 7b 87 bc 26 66 dd e3 fb b7 39 ..3.lD{..&f....9 - - Test Vector #3: - ============== - - The ChaCha20 Key - 000 1c 92 40 a5 eb 55 d3 8a f3 33 88 86 04 f6 b5 f0 ..@..U...3...... - 016 47 39 17 c1 40 2b 80 09 9d ca 5c bc 20 70 75 c0 G9..@+....\. pu. - - The nonce: - 000 00 00 00 00 00 00 00 00 00 00 00 02 ............ - - Poly1305 one-time key: - 000 96 5e 3b c6 f9 ec 7e d9 56 08 08 f4 d2 29 f9 4b .^;...~.V....).K - 016 13 7f f2 75 ca 9b 3f cb dd 59 de aa d2 33 10 ae ...u..?..Y...3.. - -A.5. ChaCha20-Poly1305 AEAD Decryption - - Below we see decrypting a message. We receive a ciphertext, a nonce, - and a tag. We know the key. We will check the tag and then - (assuming that it validates) decrypt the ciphertext. In this - particular protocol, we'll assume that there is no padding of the - plaintext. - - - - - - - - - - - - - - - - -Nir & Langley Informational [Page 42] - -RFC 8439 ChaCha20 & Poly1305 June 2018 - - - The ChaCha20 Key - 000 1c 92 40 a5 eb 55 d3 8a f3 33 88 86 04 f6 b5 f0 ..@..U...3...... - 016 47 39 17 c1 40 2b 80 09 9d ca 5c bc 20 70 75 c0 G9..@+....\. pu. - - Ciphertext: - 000 64 a0 86 15 75 86 1a f4 60 f0 62 c7 9b e6 43 bd d...u...`.b...C. - 016 5e 80 5c fd 34 5c f3 89 f1 08 67 0a c7 6c 8c b2 ^.\.4\....g..l.. - 032 4c 6c fc 18 75 5d 43 ee a0 9e e9 4e 38 2d 26 b0 Ll..u]C....N8-&. - 048 bd b7 b7 3c 32 1b 01 00 d4 f0 3b 7f 35 58 94 cf ...<2.....;.5X.. - 064 33 2f 83 0e 71 0b 97 ce 98 c8 a8 4a bd 0b 94 81 3/..q......J.... - 080 14 ad 17 6e 00 8d 33 bd 60 f9 82 b1 ff 37 c8 55 ...n..3.`....7.U - 096 97 97 a0 6e f4 f0 ef 61 c1 86 32 4e 2b 35 06 38 ...n...a..2N+5.8 - 112 36 06 90 7b 6a 7c 02 b0 f9 f6 15 7b 53 c8 67 e4 6..{j|.....{S.g. - 128 b9 16 6c 76 7b 80 4d 46 a5 9b 52 16 cd e7 a4 e9 ..lv{.MF..R..... - 144 90 40 c5 a4 04 33 22 5e e2 82 a1 b0 a0 6c 52 3e .@...3"^.....lR> - 160 af 45 34 d7 f8 3f a1 15 5b 00 47 71 8c bc 54 6a .E4..?..[.Gq..Tj - 176 0d 07 2b 04 b3 56 4e ea 1b 42 22 73 f5 48 27 1a ..+..VN..B"s.H'. - 192 0b b2 31 60 53 fa 76 99 19 55 eb d6 31 59 43 4e ..1`S.v..U..1YCN - 208 ce bb 4e 46 6d ae 5a 10 73 a6 72 76 27 09 7a 10 ..NFm.Z.s.rv'.z. - 224 49 e6 17 d9 1d 36 10 94 fa 68 f0 ff 77 98 71 30 I....6...h..w.q0 - 240 30 5b ea ba 2e da 04 df 99 7b 71 4d 6c 6f 2c 29 0[.......{qMlo,) - 256 a6 ad 5c b4 02 2b 02 70 9b ..\..+.p. - - The nonce: - 000 00 00 00 00 01 02 03 04 05 06 07 08 ............ - - The AAD: - 000 f3 33 88 86 00 00 00 00 00 00 4e 91 .3........N. - - Received Tag: - 000 ee ad 9d 67 89 0c bb 22 39 23 36 fe a1 85 1f 38 ...g..."9#6....8 - - - - - - - - - - - - - - - - - - - - -Nir & Langley Informational [Page 43] - -RFC 8439 ChaCha20 & Poly1305 June 2018 - - - First, we calculate the one-time Poly1305 key - - ChaCha state with key setup - 61707865 3320646e 79622d32 6b206574 - a540921c 8ad355eb 868833f3 f0b5f604 - c1173947 09802b40 bc5cca9d c0757020 - 00000000 00000000 04030201 08070605 - - ChaCha state after 20 rounds - a94af0bd 89dee45c b64bb195 afec8fa1 - 508f4726 63f554c0 1ea2c0db aa721526 - 11b1e514 a0bacc0f 828a6015 d7825481 - e8a4a850 d9dcbbd6 4c2de33a f8ccd912 - - out bytes: - bd:f0:4a:a9:5c:e4:de:89:95:b1:4b:b6:a1:8f:ec:af: - 26:47:8f:50:c0:54:f5:63:db:c0:a2:1e:26:15:72:aa - - Poly1305 one-time key: - 000 bd f0 4a a9 5c e4 de 89 95 b1 4b b6 a1 8f ec af ..J.\.....K..... - 016 26 47 8f 50 c0 54 f5 63 db c0 a2 1e 26 15 72 aa &G.P.T.c....&.r. - - Next, we construct the AEAD buffer - - Poly1305 Input: - 000 f3 33 88 86 00 00 00 00 00 00 4e 91 00 00 00 00 .3........N..... - 016 64 a0 86 15 75 86 1a f4 60 f0 62 c7 9b e6 43 bd d...u...`.b...C. - 032 5e 80 5c fd 34 5c f3 89 f1 08 67 0a c7 6c 8c b2 ^.\.4\....g..l.. - 048 4c 6c fc 18 75 5d 43 ee a0 9e e9 4e 38 2d 26 b0 Ll..u]C....N8-&. - 064 bd b7 b7 3c 32 1b 01 00 d4 f0 3b 7f 35 58 94 cf ...<2.....;.5X.. - 080 33 2f 83 0e 71 0b 97 ce 98 c8 a8 4a bd 0b 94 81 3/..q......J.... - 096 14 ad 17 6e 00 8d 33 bd 60 f9 82 b1 ff 37 c8 55 ...n..3.`....7.U - 112 97 97 a0 6e f4 f0 ef 61 c1 86 32 4e 2b 35 06 38 ...n...a..2N+5.8 - 128 36 06 90 7b 6a 7c 02 b0 f9 f6 15 7b 53 c8 67 e4 6..{j|.....{S.g. - 144 b9 16 6c 76 7b 80 4d 46 a5 9b 52 16 cd e7 a4 e9 ..lv{.MF..R..... - 160 90 40 c5 a4 04 33 22 5e e2 82 a1 b0 a0 6c 52 3e .@...3"^.....lR> - 176 af 45 34 d7 f8 3f a1 15 5b 00 47 71 8c bc 54 6a .E4..?..[.Gq..Tj - 192 0d 07 2b 04 b3 56 4e ea 1b 42 22 73 f5 48 27 1a ..+..VN..B"s.H'. - 208 0b b2 31 60 53 fa 76 99 19 55 eb d6 31 59 43 4e ..1`S.v..U..1YCN - 224 ce bb 4e 46 6d ae 5a 10 73 a6 72 76 27 09 7a 10 ..NFm.Z.s.rv'.z. - 240 49 e6 17 d9 1d 36 10 94 fa 68 f0 ff 77 98 71 30 I....6...h..w.q0 - 256 30 5b ea ba 2e da 04 df 99 7b 71 4d 6c 6f 2c 29 0[.......{qMlo,) - 272 a6 ad 5c b4 02 2b 02 70 9b 00 00 00 00 00 00 00 ..\..+.p........ - 288 0c 00 00 00 00 00 00 00 09 01 00 00 00 00 00 00 ................ - - - - - - - -Nir & Langley Informational [Page 44] - -RFC 8439 ChaCha20 & Poly1305 June 2018 - - - We calculate the Poly1305 tag and find that it matches - - Calculated Tag: - 000 ee ad 9d 67 89 0c bb 22 39 23 36 fe a1 85 1f 38 ...g..."9#6....8 - - Finally, we decrypt the ciphertext - - Plaintext:: - 000 49 6e 74 65 72 6e 65 74 2d 44 72 61 66 74 73 20 Internet-Drafts - 016 61 72 65 20 64 72 61 66 74 20 64 6f 63 75 6d 65 are draft docume - 032 6e 74 73 20 76 61 6c 69 64 20 66 6f 72 20 61 20 nts valid for a - 048 6d 61 78 69 6d 75 6d 20 6f 66 20 73 69 78 20 6d maximum of six m - 064 6f 6e 74 68 73 20 61 6e 64 20 6d 61 79 20 62 65 onths and may be - 080 20 75 70 64 61 74 65 64 2c 20 72 65 70 6c 61 63 updated, replac - 096 65 64 2c 20 6f 72 20 6f 62 73 6f 6c 65 74 65 64 ed, or obsoleted - 112 20 62 79 20 6f 74 68 65 72 20 64 6f 63 75 6d 65 by other docume - 128 6e 74 73 20 61 74 20 61 6e 79 20 74 69 6d 65 2e nts at any time. - 144 20 49 74 20 69 73 20 69 6e 61 70 70 72 6f 70 72 It is inappropr - 160 69 61 74 65 20 74 6f 20 75 73 65 20 49 6e 74 65 iate to use Inte - 176 72 6e 65 74 2d 44 72 61 66 74 73 20 61 73 20 72 rnet-Drafts as r - 192 65 66 65 72 65 6e 63 65 20 6d 61 74 65 72 69 61 eference materia - 208 6c 20 6f 72 20 74 6f 20 63 69 74 65 20 74 68 65 l or to cite the - 224 6d 20 6f 74 68 65 72 20 74 68 61 6e 20 61 73 20 m other than as - 240 2f e2 80 9c 77 6f 72 6b 20 69 6e 20 70 72 6f 67 /...work in prog - 256 72 65 73 73 2e 2f e2 80 9d ress./... - -Appendix B. Performance Measurements of ChaCha20 - - The following measurements were made by Adam Langley for a blog post - published on February 27th, 2014. The original blog post was - available at the time of this writing at - . - - +----------------------------+-------------+-------------------+ - | Chip | AES-128-GCM | ChaCha20-Poly1305 | - +----------------------------+-------------+-------------------+ - | OMAP 4460 | 24.1 MB/s | 75.3 MB/s | - | Snapdragon S4 Pro | 41.5 MB/s | 130.9 MB/s | - | Sandy Bridge Xeon (AES-NI) | 900 MB/s | 500 MB/s | - +----------------------------+-------------+-------------------+ - - Table 1: Speed Comparison - - - - - - - - - -Nir & Langley Informational [Page 45] - -RFC 8439 ChaCha20 & Poly1305 June 2018 - - -Acknowledgements - - ChaCha20 and Poly1305 were invented by Daniel J. Bernstein. The AEAD - construction and the method of creating the one-time Poly1305 key - were invented by Adam Langley. - - Thanks to Robert Ransom, Watson Ladd, Stefan Buhler, Dan Harkins, and - Kenny Paterson for their helpful comments and explanations. Thanks - to Niels Moller for suggesting the more efficient AEAD construction - in this document. Special thanks to Ilari Liusvaara for providing - extra test vectors, helpful comments, and for being the first to - attempt an implementation from this document. Thanks to Sean - Parkinson for suggesting improvements to the examples and the - pseudocode. Thanks to David Ireland for pointing out a bug in the - pseudocode, and to Stephen Farrell and Alyssa Rowan for pointing out - missing advise in the security considerations. - - Special thanks goes to Gordon Procter for performing a security - analysis of the composition and publishing [Procter]. - - Jim Schaad and John Mattson provided feedback on tag truncation, and - Russ Housley, Stanislav Smyshlyaev, and John Mattson each provided a - review of this version. - -Authors' Addresses - - Yoav Nir - Dell EMC - 9 Andrei Sakharov St - Haifa 3190500 - Israel - - Email: ynir.ietf@gmail.com - - - Adam Langley - Google, Inc. - - Email: agl@google.com - - - - - - - - - - - - -Nir & Langley Informational [Page 46] - diff --git a/test_crypto_debug.c b/test_crypto_debug.c deleted file mode 100644 index 86ce059d..00000000 --- a/test_crypto_debug.c +++ /dev/null @@ -1,33 +0,0 @@ -#include "nip004.h" -#include "utils.h" -#include - -int main() { - printf("Testing crypto initialization...\n"); - - if (nostr_crypto_init() != 0) { - printf("❌ Crypto init failed\n"); - return 1; - } - printf("✅ Crypto init successful\n"); - - // Test random bytes generation - unsigned char random_bytes[16]; - if (nostr_secp256k1_get_random_bytes(random_bytes, 16) != 1) { - printf("❌ Random bytes generation failed\n"); - return 1; - } - printf("✅ Random bytes generation successful\n"); - - // Test base64 encoding - char output[64]; - size_t encoded_len = base64_encode(random_bytes, 16, output, sizeof(output)); - if (encoded_len == 0) { - printf("❌ Base64 encoding failed\n"); - return 1; - } - printf("✅ Base64 encoding successful: %s\n", output); - - nostr_crypto_cleanup(); - return 0; -} diff --git a/test_vector_generator/generate_vectors.js b/test_vector_generator/generate_vectors.js deleted file mode 100644 index 33d1e12e..00000000 --- a/test_vector_generator/generate_vectors.js +++ /dev/null @@ -1,69 +0,0 @@ -const { generateSecretKey, getPublicKey, nip04 } = require('nostr-tools'); -const { bytesToHex } = require('@noble/hashes/utils'); - -function generateTestVector(testName, plaintext) { - // Generate random keys - const sk1 = generateSecretKey(); - const pk1 = getPublicKey(sk1); - const sk2 = generateSecretKey(); - const pk2 = getPublicKey(sk2); - - // Encrypt from Alice (sk1) to Bob (pk2) - const encrypted = nip04.encrypt(sk1, pk2, plaintext); - - // Verify decryption works (Bob using sk2 to decrypt from Alice pk1) - const decrypted = nip04.decrypt(sk2, pk1, encrypted); - - if (decrypted !== plaintext) { - throw new Error(`Decryption failed for ${testName}`); - } - - return { - testName, - sk1: bytesToHex(sk1), - pk1: pk1, - sk2: bytesToHex(sk2), - pk2: pk2, - plaintext: plaintext, - encrypted: encrypted - }; -} - -console.log('=== NIP-04 Test Vector Generation ===\n'); - -// Generate 3 test vectors with different plaintexts -const testVectors = [ - generateTestVector('TEST_VECTOR_2', 'Hello, NOSTR!'), - generateTestVector('TEST_VECTOR_3', 'This is a longer message to test encryption with more content. 🚀'), - generateTestVector('TEST_VECTOR_4', 'Short') -]; - -// Output in C format for easy integration -testVectors.forEach((vector, index) => { - console.log(`=== ${vector.testName}: ${vector.plaintext.replace(/\n/g, '\\n')} ===`); - console.log(`SK1 (Alice): ${vector.sk1}`); - console.log(`PK1 (Alice): ${vector.pk1}`); - console.log(`SK2 (Bob): ${vector.sk2}`); - console.log(`PK2 (Bob): ${vector.pk2}`); - console.log(`Plaintext: "${vector.plaintext}"`); - console.log(`Expected: ${vector.encrypted}`); - console.log(''); -}); - -// Also output as C code that can be copied directly -console.log('=== C CODE FOR INTEGRATION ===\n'); - -testVectors.forEach((vector, index) => { - const testNum = index + 2; // Start from 2 since we already have TEST_VECTOR_1 - console.log(` // ${vector.testName}: ${vector.plaintext.replace(/"/g, '\\"')}`); - console.log(` {`); - console.log(` "${vector.sk1}",`); - console.log(` "${vector.pk1}",`); - console.log(` "${vector.sk2}",`); - console.log(` "${vector.pk2}",`); - console.log(` "${vector.plaintext.replace(/"/g, '\\"')}",`); - console.log(` "${vector.encrypted}"`); - console.log(` }${index < testVectors.length - 1 ? ',' : ''}`); -}); - -console.log('\n=== Generation Complete ==='); diff --git a/tests/bip32_test b/tests/bip32_test index 007fec5a..663508d5 100755 Binary files a/tests/bip32_test and b/tests/bip32_test differ diff --git a/tests/crypto_test b/tests/crypto_test index c58db587..4d92cc9e 100755 Binary files a/tests/crypto_test and b/tests/crypto_test differ diff --git a/tests/http_test b/tests/http_test index 0bc63acf..8ce9ec87 100755 Binary files a/tests/http_test and b/tests/http_test differ diff --git a/tests/nip04_comparison_test b/tests/nip04_comparison_test index 478135af..168998ca 100755 Binary files a/tests/nip04_comparison_test and b/tests/nip04_comparison_test differ diff --git a/tests/nip04_test b/tests/nip04_test index 75636781..8282d490 100755 Binary files a/tests/nip04_test and b/tests/nip04_test differ diff --git a/tests/nip05_test b/tests/nip05_test index 57877996..5c8d02e5 100755 Binary files a/tests/nip05_test and b/tests/nip05_test differ diff --git a/tests/nip11_test b/tests/nip11_test index e552eb12..59a3268c 100755 Binary files a/tests/nip11_test and b/tests/nip11_test differ diff --git a/tests/nip44_test b/tests/nip44_test index 6ad9207c..f4ef9573 100755 Binary files a/tests/nip44_test and b/tests/nip44_test differ diff --git a/tests/old/nip44_debug_test.c b/tests/old/nip44_debug_test.c deleted file mode 100644 index 83583727..00000000 --- a/tests/old/nip44_debug_test.c +++ /dev/null @@ -1,249 +0,0 @@ -/* - * NIP-44 Debug Test - Step-by-step comparison with nostr-tools vectors - * - * This test prints intermediate values for comparison with nostr-tools - */ - -#include -#include -#include -#include -#include "../nostr_core/nostr_core.h" - -static int hex_to_bytes(const char* hex, unsigned char* bytes, size_t len) { - if (strlen(hex) != len * 2) return -1; - - for (size_t i = 0; i < len; i++) { - if (sscanf(hex + i * 2, "%2hhx", &bytes[i]) != 1) { - return -1; - } - } - return 0; -} - -static void bytes_to_hex(const unsigned char* bytes, size_t len, char* hex) { - for (size_t i = 0; i < len; i++) { - sprintf(hex + i * 2, "%02x", bytes[i]); - } - hex[len * 2] = '\0'; -} - -// Test a specific vector from nostr-tools -static int test_vector_step_by_step(const char* name, - const char* sec1_hex, - const char* sec2_hex, - const char* expected_conversation_key_hex, - const char* nonce_hex, - const char* plaintext, - const char* expected_payload) { - - printf("\n🔍 Testing Vector: %s\n", name); - printf("=====================================\n"); - - // Step 1: Parse keys - unsigned char sec1[32], sec2[32]; - if (hex_to_bytes(sec1_hex, sec1, 32) != 0 || hex_to_bytes(sec2_hex, sec2, 32) != 0) { - printf("❌ Failed to parse private keys\n"); - return -1; - } - - printf("📝 sec1: %s\n", sec1_hex); - printf("📝 sec2: %s\n", sec2_hex); - - // Step 2: Generate public keys - unsigned char pub1[32], pub2[32]; - if (nostr_ec_public_key_from_private_key(sec1, pub1) != 0 || - nostr_ec_public_key_from_private_key(sec2, pub2) != 0) { - printf("❌ Failed to derive public keys\n"); - return -1; - } - - char pub1_hex[65], pub2_hex[65]; - bytes_to_hex(pub1, 32, pub1_hex); - bytes_to_hex(pub2, 32, pub2_hex); - printf("📝 pub1: %s\n", pub1_hex); - printf("📝 pub2: %s\n", pub2_hex); - - // Step 3: Calculate ECDH shared secret (our raw implementation) - unsigned char shared_secret[32]; - if (ecdh_shared_secret(sec1, pub2, shared_secret) != 0) { - printf("❌ Failed to compute ECDH shared secret\n"); - return -1; - } - - char shared_hex[65]; - bytes_to_hex(shared_secret, 32, shared_hex); - printf("🔗 ECDH shared secret: %s\n", shared_hex); - - // Step 4: Calculate conversation key using HKDF-extract - unsigned char conversation_key[32]; - const char* salt_str = "nip44-v2"; - if (nostr_hkdf_extract((const unsigned char*)salt_str, strlen(salt_str), - shared_secret, 32, conversation_key) != 0) { - printf("❌ Failed to derive conversation key\n"); - return -1; - } - - char conv_key_hex[65]; - bytes_to_hex(conversation_key, 32, conv_key_hex); - printf("🗝️ Our conversation key: %s\n", conv_key_hex); - printf("🎯 Expected conv key: %s\n", expected_conversation_key_hex); - - if (strcmp(conv_key_hex, expected_conversation_key_hex) == 0) { - printf("✅ Conversation key matches!\n"); - } else { - printf("❌ Conversation key MISMATCH!\n"); - return -1; - } - - // Step 5: Parse nonce - unsigned char nonce[32]; - if (hex_to_bytes(nonce_hex, nonce, 32) != 0) { - printf("❌ Failed to parse nonce\n"); - return -1; - } - printf("🎲 Nonce: %s\n", nonce_hex); - - // Step 6: Derive message keys using HKDF-expand - unsigned char message_keys[76]; // 32 chacha_key + 12 chacha_nonce + 32 hmac_key - if (nostr_hkdf_expand(conversation_key, 32, nonce, 32, message_keys, 76) != 0) { - printf("❌ Failed to derive message keys\n"); - return -1; - } - - char chacha_key_hex[65], chacha_nonce_hex[25], hmac_key_hex[65]; - bytes_to_hex(message_keys, 32, chacha_key_hex); - bytes_to_hex(message_keys + 32, 12, chacha_nonce_hex); - bytes_to_hex(message_keys + 44, 32, hmac_key_hex); - - printf("🔐 ChaCha key: %s\n", chacha_key_hex); - printf("🔐 ChaCha nonce: %s\n", chacha_nonce_hex); - printf("🔐 HMAC key: %s\n", hmac_key_hex); - - // Step 7: Test encryption with known nonce - char our_payload[8192]; - int encrypt_result = nostr_nip44_encrypt_with_nonce(sec1, pub2, plaintext, nonce, our_payload, sizeof(our_payload)); - - if (encrypt_result == NOSTR_SUCCESS) { - printf("🔒 Our payload: %s\n", our_payload); - printf("🎯 Expected payload: %s\n", expected_payload); - - if (strcmp(our_payload, expected_payload) == 0) { - printf("✅ Payload matches perfectly!\n"); - } else { - printf("❌ Payload MISMATCH!\n"); - - // Try to decrypt expected payload with our conversation key - printf("\n🔍 Debugging: Trying to decrypt expected payload...\n"); - char decrypted[8192]; - int decrypt_result = nostr_nip44_decrypt(sec2, pub1, expected_payload, decrypted, sizeof(decrypted)); - - if (decrypt_result == NOSTR_SUCCESS) { - printf("✅ Successfully decrypted expected payload!\n"); - printf("📝 Decrypted text: \"%s\"\n", decrypted); - if (strcmp(decrypted, plaintext) == 0) { - printf("✅ Decrypted text matches original!\n"); - } else { - printf("❌ Decrypted text doesn't match original!\n"); - } - } else { - printf("❌ Failed to decrypt expected payload (error: %d)\n", decrypt_result); - } - } - } else { - printf("❌ Encryption failed with error: %d\n", encrypt_result); - return -1; - } - - return 0; -} - -int main() { - printf("🧪 NIP-44 Debug Test - Step-by-step Vector Comparison\n"); - printf("======================================================\n"); - - // Initialize the library - if (nostr_init() != NOSTR_SUCCESS) { - printf("❌ Failed to initialize NOSTR library\n"); - return 1; - } - - // Test the simple "a" vector - test_vector_step_by_step( - "Single char 'a'", - "0000000000000000000000000000000000000000000000000000000000000001", - "0000000000000000000000000000000000000000000000000000000000000002", - "c41c775356fd92eadc63ff5a0dc1da211b268cbea22316767095b2871ea1412d", - "0000000000000000000000000000000000000000000000000000000000000001", - "a", - "AgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABee0G5VSK0/9YypIObAtDKfYEAjD35uVkHyB0F4DwrcNaCXlCWZKaArsGrY6M9wnuTMxWfp1RTN9Xga8no+kF5Vsb" - ); - - // Test the emoji vector - test_vector_step_by_step( - "Emoji 🍕🫃", - "0000000000000000000000000000000000000000000000000000000000000002", - "0000000000000000000000000000000000000000000000000000000000000001", - "c41c775356fd92eadc63ff5a0dc1da211b268cbea22316767095b2871ea1412d", - "f00000000000000000000000000000f00000000000000000000000000000000f", - "🍕🫃", - "AvAAAAAAAAAAAAAAAAAAAPAAAAAAAAAAAAAAAAAAAAAPSKSK6is9ngkX2+cSq85Th16oRTISAOfhStnixqZziKMDvB0QQzgFZdjLTPicCJaV8nDITO+QfaQ61+KbWQIOO2Yj" - ); - - // Test with get_message_keys test vector to verify HKDF-expand - printf("\n🔍 Testing get_message_keys vector from nostr-tools:\n"); - printf("===========================================\n"); - - unsigned char conv_key[32]; - if (hex_to_bytes("a1a3d60f3470a8612633924e91febf96dc5366ce130f658b1f0fc652c20b3b54", conv_key, 32) == 0) { - unsigned char test_nonce[32]; - if (hex_to_bytes("e1e6f880560d6d149ed83dcc7e5861ee62a5ee051f7fde9975fe5d25d2a02d72", test_nonce, 32) == 0) { - - unsigned char message_keys[76]; - if (nostr_hkdf_expand(conv_key, 32, test_nonce, 32, message_keys, 76) == 0) { - - char chacha_key_hex[65], chacha_nonce_hex[25], hmac_key_hex[65]; - bytes_to_hex(message_keys, 32, chacha_key_hex); - bytes_to_hex(message_keys + 32, 12, chacha_nonce_hex); - bytes_to_hex(message_keys + 44, 32, hmac_key_hex); - - printf("📝 Conv key: a1a3d60f3470a8612633924e91febf96dc5366ce130f658b1f0fc652c20b3b54\n"); - printf("📝 Nonce: e1e6f880560d6d149ed83dcc7e5861ee62a5ee051f7fde9975fe5d25d2a02d72\n"); - printf("🔐 Our ChaCha key: %s\n", chacha_key_hex); - printf("🎯 Expected ChaCha key: f145f3bed47cb70dbeaac07f3a3fe683e822b3715edb7c4fe310829014ce7d76\n"); - printf("🔐 Our ChaCha nonce: %s\n", chacha_nonce_hex); - printf("🎯 Expected ChaCha nonce: c4ad129bb01180c0933a160c\n"); - printf("🔐 Our HMAC key: %s\n", hmac_key_hex); - printf("🎯 Expected HMAC key: 027c1db445f05e2eee864a0975b0ddef5b7110583c8c192de3732571ca5838c4\n"); - - if (strcmp(chacha_key_hex, "f145f3bed47cb70dbeaac07f3a3fe683e822b3715edb7c4fe310829014ce7d76") == 0) { - printf("✅ ChaCha key matches!\n"); - } else { - printf("❌ ChaCha key MISMATCH!\n"); - } - - if (strcmp(chacha_nonce_hex, "c4ad129bb01180c0933a160c") == 0) { - printf("✅ ChaCha nonce matches!\n"); - } else { - printf("❌ ChaCha nonce MISMATCH!\n"); - } - - if (strcmp(hmac_key_hex, "027c1db445f05e2eee864a0975b0ddef5b7110583c8c192de3732571ca5838c4") == 0) { - printf("✅ HMAC key matches!\n"); - } else { - printf("❌ HMAC key MISMATCH!\n"); - } - } else { - printf("❌ Failed to expand message keys\n"); - } - } else { - printf("❌ Failed to parse test nonce\n"); - } - } else { - printf("❌ Failed to parse conversation key\n"); - } - - nostr_cleanup(); - printf("\n🏁 Debug test completed\n"); - return 0; -} diff --git a/tests/old/nip44_detailed_debug_test.c b/tests/old/nip44_detailed_debug_test.c deleted file mode 100644 index 0ecc83b7..00000000 --- a/tests/old/nip44_detailed_debug_test.c +++ /dev/null @@ -1,255 +0,0 @@ -/* - * NIP-44 Detailed Debug Test - Print every single intermediate step - */ - -#include -#include -#include -#include -#include "../nostr_core/nostr_core.h" - -static int hex_to_bytes(const char* hex, unsigned char* bytes, size_t len) { - if (strlen(hex) != len * 2) return -1; - - for (size_t i = 0; i < len; i++) { - if (sscanf(hex + i * 2, "%2hhx", &bytes[i]) != 1) { - return -1; - } - } - return 0; -} - -static void bytes_to_hex(const unsigned char* bytes, size_t len, char* hex) { - for (size_t i = 0; i < len; i++) { - sprintf(hex + i * 2, "%02x", bytes[i]); - } - hex[len * 2] = '\0'; -} - -static void print_bytes(const char* label, const unsigned char* bytes, size_t len) { - char hex[len * 2 + 1]; - bytes_to_hex(bytes, len, hex); - printf("%s: %s\n", label, hex); -} - -// Test NIP-44 padding calculation (replicate from our crypto.c) -static size_t calc_padded_len(size_t unpadded_len) { - if (unpadded_len <= 32) { - return 32; - } - - size_t next_power = 1; - while (next_power < unpadded_len) { - next_power <<= 1; - } - - size_t chunk = (next_power <= 256) ? 32 : (next_power / 8); - return chunk * ((unpadded_len - 1) / chunk + 1); -} - -// Test NIP-44 padding (replicate from our crypto.c) -static unsigned char* pad_plaintext_debug(const char* plaintext, size_t* padded_len) { - size_t unpadded_len = strlen(plaintext); - if (unpadded_len > 65535) { - return NULL; - } - - printf("🔍 PADDING DEBUG:\n"); - printf(" unpadded_len: %zu\n", unpadded_len); - - *padded_len = calc_padded_len(unpadded_len + 2); // +2 for length prefix - printf(" calculated_padded_len: %zu\n", *padded_len); - - unsigned char* padded = malloc(*padded_len); - if (!padded) return NULL; - - // Write length prefix (big-endian u16) - padded[0] = (unpadded_len >> 8) & 0xFF; - padded[1] = unpadded_len & 0xFF; - printf(" length_prefix: %02x%02x (big-endian u16 = %zu)\n", padded[0], padded[1], unpadded_len); - - // Copy plaintext (if any) - if (unpadded_len > 0) { - memcpy(padded + 2, plaintext, unpadded_len); - } - - // Zero-fill padding - memset(padded + 2 + unpadded_len, 0, *padded_len - 2 - unpadded_len); - - print_bytes(" padded_plaintext", padded, *padded_len); - - return padded; -} - -int main() { - printf("🧪 NIP-44 DETAILED DEBUG TEST\n"); - printf("===============================\n\n"); - - // Initialize the library - if (nostr_init() != NOSTR_SUCCESS) { - printf("❌ Failed to initialize NOSTR library\n"); - return 1; - } - - printf("=== TESTING: Single char 'a' ===\n"); - - // Step 1: Parse private keys - unsigned char sec1[32], sec2[32]; - hex_to_bytes("0000000000000000000000000000000000000000000000000000000000000001", sec1, 32); - hex_to_bytes("0000000000000000000000000000000000000000000000000000000000000002", sec2, 32); - - print_bytes("sec1", sec1, 32); - print_bytes("sec2", sec2, 32); - - // Step 2: Generate public keys - unsigned char pub1[32], pub2[32]; - nostr_ec_public_key_from_private_key(sec1, pub1); - nostr_ec_public_key_from_private_key(sec2, pub2); - - print_bytes("pub1", pub1, 32); - print_bytes("pub2", pub2, 32); - - // Step 3: ECDH shared secret - unsigned char shared_secret[32]; - ecdh_shared_secret(sec1, pub2, shared_secret); - print_bytes("ecdh_shared_secret", shared_secret, 32); - - // Step 4: HKDF Extract (conversation key) - unsigned char conversation_key[32]; - const char* salt_str = "nip44-v2"; - nostr_hkdf_extract((const unsigned char*)salt_str, strlen(salt_str), shared_secret, 32, conversation_key); - print_bytes("conversation_key", conversation_key, 32); - - // Step 5: Parse nonce - unsigned char nonce[32]; - hex_to_bytes("0000000000000000000000000000000000000000000000000000000000000001", nonce, 32); - print_bytes("nonce", nonce, 32); - - // Step 6: HKDF Expand (message keys) - unsigned char message_keys[76]; - nostr_hkdf_expand(conversation_key, 32, nonce, 32, message_keys, 76); - - print_bytes("chacha_key", message_keys, 32); - print_bytes("chacha_nonce", message_keys + 32, 12); - print_bytes("hmac_key", message_keys + 44, 32); - - // Step 7: Pad plaintext - const char* plaintext = "a"; - printf("\n🔍 PLAINTEXT: \"%s\" (length: %zu)\n", plaintext, strlen(plaintext)); - - size_t padded_len; - unsigned char* padded_plaintext = pad_plaintext_debug(plaintext, &padded_len); - if (!padded_plaintext) { - printf("❌ Failed to pad plaintext\n"); - return 1; - } - - // Step 8: ChaCha20 encrypt - printf("\n🔍 CHACHA20 ENCRYPTION:\n"); - unsigned char* ciphertext = malloc(padded_len); - if (!ciphertext) { - printf("❌ Failed to allocate ciphertext buffer\n"); - free(padded_plaintext); - return 1; - } - - // Use our ChaCha20 function - if (chacha20_encrypt(message_keys, 0, message_keys + 32, padded_plaintext, ciphertext, padded_len) != 0) { - printf("❌ ChaCha20 encryption failed\n"); - free(padded_plaintext); - free(ciphertext); - return 1; - } - - print_bytes(" ciphertext", ciphertext, padded_len); - - // Step 9: HMAC with AAD - printf("\n🔍 HMAC CALCULATION:\n"); - unsigned char* aad_data = malloc(32 + padded_len); - if (!aad_data) { - printf("❌ Failed to allocate AAD buffer\n"); - free(padded_plaintext); - free(ciphertext); - return 1; - } - - memcpy(aad_data, nonce, 32); - memcpy(aad_data + 32, ciphertext, padded_len); - print_bytes(" aad_data", aad_data, 32 + padded_len); - - unsigned char mac[32]; - nostr_hmac_sha256(message_keys + 44, 32, aad_data, 32 + padded_len, mac); - print_bytes(" mac", mac, 32); - - // Step 10: Construct final payload - printf("\n🔍 PAYLOAD CONSTRUCTION:\n"); - size_t payload_len = 1 + 32 + padded_len + 32; - unsigned char* payload = malloc(payload_len); - if (!payload) { - printf("❌ Failed to allocate payload buffer\n"); - free(padded_plaintext); - free(ciphertext); - free(aad_data); - return 1; - } - - payload[0] = 0x02; // NIP-44 version 2 - memcpy(payload + 1, nonce, 32); - memcpy(payload + 33, ciphertext, padded_len); - memcpy(payload + 33 + padded_len, mac, 32); - - printf(" version: 0x%02x\n", payload[0]); - print_bytes(" payload_nonce", payload + 1, 32); - print_bytes(" payload_ciphertext", payload + 33, padded_len); - print_bytes(" payload_mac", payload + 33 + padded_len, 32); - print_bytes(" raw_payload", payload, payload_len); - - // Step 11: Base64 encode - printf("\n🔍 BASE64 ENCODING:\n"); - size_t b64_len = ((payload_len + 2) / 3) * 4 + 1; - char* base64_output = malloc(b64_len); - if (!base64_output) { - printf("❌ Failed to allocate base64 buffer\n"); - free(padded_plaintext); - free(ciphertext); - free(aad_data); - free(payload); - return 1; - } - - // Use our internal base64_encode function from crypto.c - extern size_t base64_encode(const unsigned char* data, size_t len, char* output, size_t output_size); - size_t actual_b64_len = base64_encode(payload, payload_len, base64_output, b64_len); - - printf(" payload_length: %zu\n", payload_len); - printf(" base64_length: %zu\n", actual_b64_len); - printf(" our_base64: %s\n", base64_output); - printf(" expected: AgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABee0G5VSK0/9YypIObAtDKfYEAjD35uVkHyB0F4DwrcNaCXlCWZKaArsGrY6M9wnuTMxWfp1RTN9Xga8no+kF5Vsb\n"); - - if (strcmp(base64_output, "AgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABee0G5VSK0/9YypIObAtDKfYEAjD35uVkHyB0F4DwrcNaCXlCWZKaArsGrY6M9wnuTMxWfp1RTN9Xga8no+kF5Vsb") == 0) { - printf("✅ PERFECT MATCH!\n"); - } else { - printf("❌ MISMATCH - need to investigate!\n"); - - // Let's also try our full encrypt function for comparison - printf("\n🔍 FULL ENCRYPT FUNCTION TEST:\n"); - char full_encrypt_output[8192]; - int result = nostr_nip44_encrypt_with_nonce(sec1, pub2, plaintext, nonce, full_encrypt_output, sizeof(full_encrypt_output)); - if (result == NOSTR_SUCCESS) { - printf(" full_encrypt: %s\n", full_encrypt_output); - } else { - printf(" full_encrypt failed with error: %d\n", result); - } - } - - // Cleanup - free(padded_plaintext); - free(ciphertext); - free(aad_data); - free(payload); - free(base64_output); - - nostr_cleanup(); - printf("\n🏁 Detailed debug test completed\n"); - return 0; -} diff --git a/tests/old/simple_nip44_test.c b/tests/old/simple_nip44_test.c deleted file mode 100644 index 71061550..00000000 --- a/tests/old/simple_nip44_test.c +++ /dev/null @@ -1,118 +0,0 @@ -/* - * Simple NIP-44 Test - * Basic functionality test for NIP-44 encryption/decryption - */ - -#include -#include -#include -#include "../nostr_core/nostr_core.h" - -int main() { - printf("🧪 Simple NIP-44 Test\n"); - printf("=====================\n\n"); - - // Initialize the library - if (nostr_init() != NOSTR_SUCCESS) { - printf("❌ Failed to initialize NOSTR library\n"); - return 1; - } - - // Test keys (from successful NIP-04 test) - const char* sender_key_hex = "91ba716fa9e7ea2fcbad360cf4f8e0d312f73984da63d90f524ad61a6a1e7dbe"; - const char* recipient_key_hex = "96f6fa197aa07477ab88f6981118466ae3a982faab8ad5db9d5426870c73d220"; - - unsigned char sender_private_key[32]; - unsigned char recipient_private_key[32]; - unsigned char recipient_public_key[32]; - - // Parse keys - if (nostr_hex_to_bytes(sender_key_hex, sender_private_key, 32) != 0) { - printf("❌ Failed to parse sender private key\n"); - nostr_cleanup(); - return 1; - } - - if (nostr_hex_to_bytes(recipient_key_hex, recipient_private_key, 32) != 0) { - printf("❌ Failed to parse recipient private key\n"); - nostr_cleanup(); - return 1; - } - - // Generate recipient's public key - if (nostr_ec_public_key_from_private_key(recipient_private_key, recipient_public_key) != 0) { - printf("❌ Failed to generate recipient public key\n"); - nostr_cleanup(); - return 1; - } - - printf("✅ Keys parsed successfully\n"); - - // Test message - const char* test_message = "Hello, NIP-44! This is a test message."; - printf("📝 Test message: \"%s\"\n", test_message); - - // Test encryption - char encrypted[8192]; - printf("🔐 Testing NIP-44 encryption...\n"); - int encrypt_result = nostr_nip44_encrypt( - sender_private_key, - recipient_public_key, - test_message, - encrypted, - sizeof(encrypted) - ); - - if (encrypt_result != NOSTR_SUCCESS) { - printf("❌ NIP-44 encryption failed with error: %d\n", encrypt_result); - nostr_cleanup(); - return 1; - } - - printf("✅ NIP-44 encryption successful!\n"); - printf("📦 Encrypted length: %zu bytes\n", strlen(encrypted)); - printf("📦 First 80 chars: %.80s...\n", encrypted); - - // Test decryption - char decrypted[8192]; - unsigned char sender_public_key[32]; - - // Generate sender's public key for decryption - if (nostr_ec_public_key_from_private_key(sender_private_key, sender_public_key) != 0) { - printf("❌ Failed to generate sender public key\n"); - nostr_cleanup(); - return 1; - } - - printf("🔓 Testing NIP-44 decryption...\n"); - int decrypt_result = nostr_nip44_decrypt( - recipient_private_key, - sender_public_key, - encrypted, - decrypted, - sizeof(decrypted) - ); - - if (decrypt_result != NOSTR_SUCCESS) { - printf("❌ NIP-44 decryption failed with error: %d\n", decrypt_result); - nostr_cleanup(); - return 1; - } - - printf("✅ NIP-44 decryption successful!\n"); - printf("📝 Decrypted: \"%s\"\n", decrypted); - - // Verify round-trip - if (strcmp(test_message, decrypted) == 0) { - printf("✅ Round-trip successful! Messages match perfectly.\n"); - printf("\n🎉 NIP-44 TEST PASSED! 🎉\n"); - nostr_cleanup(); - return 0; - } else { - printf("❌ Round-trip failed! Messages don't match.\n"); - printf("📝 Original: \"%s\"\n", test_message); - printf("📝 Decrypted: \"%s\"\n", decrypted); - nostr_cleanup(); - return 1; - } -} diff --git a/tests/simple_init_test b/tests/simple_init_test index 97f425c8..e4b4ab94 100755 Binary files a/tests/simple_init_test and b/tests/simple_init_test differ diff --git a/tests/sync_relay_test b/tests/sync_relay_test index ab19d9e6..aa39a1a0 100755 Binary files a/tests/sync_relay_test and b/tests/sync_relay_test differ diff --git a/tests/wss_test b/tests/wss_test index dd641486..c01992fd 100755 Binary files a/tests/wss_test and b/tests/wss_test differ