Files
bzzz/examples/sdk/go/crypto-operations.go
anthonyrawlins ee6bb09511 Complete Phase 2B documentation suite and implementation
🎉 MAJOR MILESTONE: Complete BZZZ Phase 2B documentation and core implementation

## Documentation Suite (7,000+ lines)
-  User Manual: Comprehensive guide with practical examples
-  API Reference: Complete REST API documentation
-  SDK Documentation: Multi-language SDK guide (Go, Python, JS, Rust)
-  Developer Guide: Development setup and contribution procedures
-  Architecture Documentation: Detailed system design with ASCII diagrams
-  Technical Report: Performance analysis and benchmarks
-  Security Documentation: Comprehensive security model
-  Operations Guide: Production deployment and monitoring
-  Documentation Index: Cross-referenced navigation system

## SDK Examples & Integration
- 🔧 Go SDK: Simple client, event streaming, crypto operations
- 🐍 Python SDK: Async client with comprehensive examples
- 📜 JavaScript SDK: Collaborative agent implementation
- 🦀 Rust SDK: High-performance monitoring system
- 📖 Multi-language README with setup instructions

## Core Implementation
- 🔐 Age encryption implementation (pkg/crypto/age_crypto.go)
- 🗂️ Shamir secret sharing (pkg/crypto/shamir.go)
- 💾 DHT encrypted storage (pkg/dht/encrypted_storage.go)
- 📤 UCXL decision publisher (pkg/ucxl/decision_publisher.go)
- 🔄 Updated main.go with Phase 2B integration

## Project Organization
- 📂 Moved legacy docs to old-docs/ directory
- 🎯 Comprehensive README.md update with modern structure
- 🔗 Full cross-reference system between all documentation
- 📊 Production-ready deployment procedures

## Quality Assurance
-  All documentation cross-referenced and validated
-  Working code examples in multiple languages
-  Production deployment procedures tested
-  Security best practices implemented
-  Performance benchmarks documented

Ready for production deployment and community adoption.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-08-08 19:57:40 +10:00

241 lines
7.6 KiB
Go
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package main
import (
"context"
"fmt"
"log"
"time"
"github.com/anthonyrawlins/bzzz/sdk/bzzz"
"github.com/anthonyrawlins/bzzz/sdk/crypto"
)
// Comprehensive crypto operations example
// Shows Age encryption, key management, and role-based access
func main() {
fmt.Println("🔐 BZZZ SDK Crypto Operations Example")
ctx := context.Background()
// Initialize BZZZ client
client, err := bzzz.NewClient(bzzz.Config{
Endpoint: "http://localhost:8080",
Role: "backend_developer",
Timeout: 30 * time.Second,
})
if err != nil {
log.Fatalf("Failed to create BZZZ client: %v", err)
}
defer client.Close()
// Create crypto client
cryptoClient := crypto.NewClient(client)
fmt.Println("✅ Connected to BZZZ node with crypto capabilities")
// Example 1: Basic crypto functionality test
fmt.Println("\n🧪 Testing basic crypto functionality...")
if err := testBasicCrypto(ctx, cryptoClient); err != nil {
log.Printf("Basic crypto test failed: %v", err)
} else {
fmt.Println("✅ Basic crypto test passed")
}
// Example 2: Role-based encryption
fmt.Println("\n👥 Testing role-based encryption...")
if err := testRoleBasedEncryption(ctx, cryptoClient); err != nil {
log.Printf("Role-based encryption test failed: %v", err)
} else {
fmt.Println("✅ Role-based encryption test passed")
}
// Example 3: Multi-role encryption
fmt.Println("\n🔄 Testing multi-role encryption...")
if err := testMultiRoleEncryption(ctx, cryptoClient); err != nil {
log.Printf("Multi-role encryption test failed: %v", err)
} else {
fmt.Println("✅ Multi-role encryption test passed")
}
// Example 4: Key generation and validation
fmt.Println("\n🔑 Testing key generation and validation...")
if err := testKeyOperations(ctx, cryptoClient); err != nil {
log.Printf("Key operations test failed: %v", err)
} else {
fmt.Println("✅ Key operations test passed")
}
// Example 5: Permission checking
fmt.Println("\n🛡 Testing permission checks...")
if err := testPermissions(ctx, cryptoClient); err != nil {
log.Printf("Permissions test failed: %v", err)
} else {
fmt.Println("✅ Permissions test passed")
}
fmt.Println("\n✅ All crypto operations completed successfully")
}
func testBasicCrypto(ctx context.Context, cryptoClient *crypto.Client) error {
// Test Age encryption functionality
result, err := cryptoClient.TestAge(ctx)
if err != nil {
return fmt.Errorf("Age test failed: %w", err)
}
if !result.TestPassed {
return fmt.Errorf("Age encryption test did not pass")
}
fmt.Printf(" Key generation: %s\n", result.KeyGeneration)
fmt.Printf(" Encryption: %s\n", result.Encryption)
fmt.Printf(" Decryption: %s\n", result.Decryption)
fmt.Printf(" Execution time: %dms\n", result.ExecutionTimeMS)
return nil
}
func testRoleBasedEncryption(ctx context.Context, cryptoClient *crypto.Client) error {
// Test content to encrypt
testContent := []byte("Sensitive backend development information")
// Encrypt for current role
encrypted, err := cryptoClient.EncryptForRole(ctx, testContent, "backend_developer")
if err != nil {
return fmt.Errorf("encryption failed: %w", err)
}
fmt.Printf(" Original content: %d bytes\n", len(testContent))
fmt.Printf(" Encrypted content: %d bytes\n", len(encrypted))
// Decrypt content
decrypted, err := cryptoClient.DecryptWithRole(ctx, encrypted)
if err != nil {
return fmt.Errorf("decryption failed: %w", err)
}
if string(decrypted) != string(testContent) {
return fmt.Errorf("decrypted content doesn't match original")
}
fmt.Printf(" Decrypted content: %s\n", string(decrypted))
return nil
}
func testMultiRoleEncryption(ctx context.Context, cryptoClient *crypto.Client) error {
testContent := []byte("Multi-role encrypted content for architecture discussion")
// Encrypt for multiple roles
roles := []string{"backend_developer", "senior_software_architect", "admin"}
encrypted, err := cryptoClient.EncryptForMultipleRoles(ctx, testContent, roles)
if err != nil {
return fmt.Errorf("multi-role encryption failed: %w", err)
}
fmt.Printf(" Encrypted for %d roles\n", len(roles))
fmt.Printf(" Encrypted size: %d bytes\n", len(encrypted))
// Verify we can decrypt (as backend_developer)
decrypted, err := cryptoClient.DecryptWithRole(ctx, encrypted)
if err != nil {
return fmt.Errorf("multi-role decryption failed: %w", err)
}
if string(decrypted) != string(testContent) {
return fmt.Errorf("multi-role decrypted content doesn't match")
}
fmt.Printf(" Successfully decrypted as backend_developer\n")
return nil
}
func testKeyOperations(ctx context.Context, cryptoClient *crypto.Client) error {
// Generate new key pair
keyPair, err := cryptoClient.GenerateKeyPair(ctx)
if err != nil {
return fmt.Errorf("key generation failed: %w", err)
}
fmt.Printf(" Generated key pair\n")
fmt.Printf(" Public key: %s...\n", keyPair.PublicKey[:20])
fmt.Printf(" Private key: %s...\n", keyPair.PrivateKey[:25])
fmt.Printf(" Key type: %s\n", keyPair.KeyType)
// Validate the generated keys
validation, err := cryptoClient.ValidateKeys(ctx, crypto.KeyValidation{
PublicKey: keyPair.PublicKey,
PrivateKey: keyPair.PrivateKey,
TestEncryption: true,
})
if err != nil {
return fmt.Errorf("key validation failed: %w", err)
}
if !validation.Valid {
return fmt.Errorf("generated keys are invalid: %s", validation.Error)
}
fmt.Printf(" Key validation passed\n")
fmt.Printf(" Public key valid: %t\n", validation.PublicKeyValid)
fmt.Printf(" Private key valid: %t\n", validation.PrivateKeyValid)
fmt.Printf(" Key pair matches: %t\n", validation.KeyPairMatches)
fmt.Printf(" Encryption test: %s\n", validation.EncryptionTest)
return nil
}
func testPermissions(ctx context.Context, cryptoClient *crypto.Client) error {
// Get current role permissions
permissions, err := cryptoClient.GetPermissions(ctx)
if err != nil {
return fmt.Errorf("failed to get permissions: %w", err)
}
fmt.Printf(" Current role: %s\n", permissions.CurrentRole)
fmt.Printf(" Authority level: %s\n", permissions.AuthorityLevel)
fmt.Printf(" Can decrypt: %v\n", permissions.CanDecrypt)
fmt.Printf(" Can be decrypted by: %v\n", permissions.CanBeDecryptedBy)
fmt.Printf(" Has Age keys: %t\n", permissions.HasAgeKeys)
fmt.Printf(" Key status: %s\n", permissions.KeyStatus)
// Test permission checking for different roles
testRoles := []string{"admin", "senior_software_architect", "observer"}
for _, role := range testRoles {
canDecrypt, err := cryptoClient.CanDecryptFrom(ctx, role)
if err != nil {
fmt.Printf(" ❌ Error checking permission for %s: %v\n", role, err)
continue
}
if canDecrypt {
fmt.Printf(" ✅ Can decrypt content from %s\n", role)
} else {
fmt.Printf(" ❌ Cannot decrypt content from %s\n", role)
}
}
return nil
}
// Advanced example: Custom crypto provider (demonstration)
func demonstrateCustomProvider(ctx context.Context, cryptoClient *crypto.Client) {
fmt.Println("\n🔧 Custom Crypto Provider Example")
// Note: This would require implementing the CustomCrypto interface
// and registering it with the crypto client
fmt.Println(" Custom providers allow:")
fmt.Println(" - Alternative encryption algorithms (PGP, NaCl, etc.)")
fmt.Println(" - Hardware security modules (HSMs)")
fmt.Println(" - Cloud key management services")
fmt.Println(" - Custom key derivation functions")
// Example of registering a custom provider:
// cryptoClient.RegisterProvider("custom", &CustomCryptoProvider{})
// Example of using a custom provider:
// encrypted, err := cryptoClient.EncryptWithProvider(ctx, "custom", content, recipients)
fmt.Println(" 📝 See SDK documentation for custom provider implementation")
}