gopki

module
v1.25.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 19, 2026 License: MIT

README ΒΆ

GoPKI

Go Version Test Coverage Go Report Card

Production-ready Go library for PKI operations with type-safe cryptography through Go generics. Full X.509, PKCS#7/CMS, PKCS#12, SSH, and JOSE (JWT/JWS/JWE/JWK) support with 80.3% test coverage across 900+ tests.

✨ Why GoPKI?

  • πŸ”’ Type-Safe Cryptography: Go generics eliminate any/interface{} types for compile-time safety
  • πŸ›‘οΈ Security-First: Enforced minimum key sizes, secure file permissions, memory-safe APIs
  • πŸ“œ Standards Compliant: Full RFC compliance (X.509, CMS, PKCS#7, PKCS#12, SSH)
  • 🀝 Battle-Tested: 95%+ OpenSSL compatibility, 100% OpenSSH compatibility
  • ⚑ Production Ready: 80.3% test coverage, comprehensive CI/CD, semantic versioning

πŸ“¦ Installation

go get github.com/jasoet/gopki

Requirements: Go 1.24.5+

πŸ€– AI Agent Instructions

If you're an AI assistant working on this codebase, start here:

πŸ“– Comprehensive AI Navigation Guide

For complete AI agent guidance, read:

This README provides a quick reference. For detailed navigation paths, common bug patterns, module interaction patterns, and troubleshooting guides, see the AI Navigation document.

Quick Navigation by Task
Task Read First Read Next Key Files
Key Generation/Management keypair/README.md docs/ALGORITHMS.md keypair/keypair.go, keypair/algo/*.go
Encryption Features encryption/README.md docs/ENCRYPTION_GUIDE.md encryption/envelope/, encryption/asymmetric/
Digital Signatures signing/README.md docs/OPENSSL_COMPAT.md signing/signer.go, signing/formats/
Certificate Operations cert/README.md Certificate examples cert/cert.go, cert/ca.go
PKCS#12 Files pkcs12/README.md Module tests pkcs12/pkcs12.go
JOSE (JWT/JWS/JWE/JWK) jose/README.md JOSE modules jose/jwt/, jose/jws/, jose/jwe/, jose/jwk/
OpenSSL Compatibility docs/OPENSSL_COMPAT.md compatibility/ tests compatibility/helpers.go
Testing Taskfile.yml Module-specific tests *_test.go files
Understanding the Architecture

Step 1: Core Concepts

  • Read docs/ARCHITECTURE.md - System design and module relationships
  • Review CLAUDE.md - Detailed development guidelines and patterns
  • Check module dependency diagram below

Step 2: Type System

  • GoPKI uses Go generics extensively for type safety
  • Key type constraints defined in keypair/keypair.go:50-150
  • All modules follow these type patterns - review them first

Step 3: Format Support

  • PEM, DER, SSH, PKCS#12 formats all supported
  • Format conversion logic in format/ package
  • See module-specific READMEs for conversion patterns
Common Modification Patterns

Adding New Algorithm Support:

  1. Read existing algorithm implementation in relevant algo/ directory
  2. Check test patterns in *_algo_test.go
  3. Verify compatibility test requirements in compatibility/
  4. Update format conversion functions
  5. Add to documentation and examples

Fixing Bugs:

  1. Start with tests - Read *_test.go files first to understand expected behavior
  2. Check recent changes: git log --oneline -10 <file>
  3. Review error handling patterns in similar functions
  4. Run specific tests: task test:specific -- TestName
  5. Verify compatibility: task test:compatibility

Adding OpenSSL Compatibility:

  1. Read docs/OPENSSL_COMPAT.md for current status
  2. Review compatibility/helpers.go for OpenSSL integration patterns
  3. Add test in appropriate compatibility/*/ directory
  4. Update docs/COMPATIBILITY_REPORT.md with findings
Code Reading Order for New AI Agents

First Session (Core Understanding):

1. README.md (this file) - Project overview
2. CLAUDE.md - Development guidelines
3. docs/ARCHITECTURE.md - System design
4. keypair/README.md - Foundation module
5. encryption/README.md - Most complex module

For Specific Features:

Certificate Operations:
  cert/README.md β†’ cert/cert.go β†’ cert/ca.go β†’ examples/certificates/

Encryption:
  encryption/README.md β†’ encryption/envelope/envelope.go β†’
  encryption/asymmetric/*.go β†’ compatibility/encryption/

Signing:
  signing/README.md β†’ signing/signer.go β†’ signing/formats/pkcs7.go β†’
  examples/signing/
Key Files Map

Core Type Definitions:

  • keypair/keypair.go:50-150 - Generic type constraints (START HERE)
  • encryption/types.go - Encryption types
  • signing/types.go - Signature types
  • cert/types.go - Certificate types

Main Implementations:

  • keypair/manager.go - Key pair management
  • encryption/envelope/envelope.go:150-450 - Envelope encryption
  • signing/signer.go:100-300 - Document signing
  • cert/ca.go:75-250 - Certificate authority operations

Testing Infrastructure:

  • compatibility/helpers.go - OpenSSL integration utilities
  • *_test.go - Unit tests (80.3% coverage)
  • examples/*/main.go - Integration examples
Project Conventions

Type Safety:

  • No any/interface{} in core APIs (exceptions: metadata maps only)
  • Use generic constraints from keypair/keypair.go
  • Compile-time type checking enforced

Security:

  • Minimum RSA key size: 2048 bits (enforced)
  • File permissions: 0600 (private keys), 0700 (directories)
  • No raw key material exposure in APIs

Error Handling:

  • All functions return explicit errors (no panics)
  • Errors wrapped with context: fmt.Errorf("context: %w", err)

Testing:

  • Run tests before changes: task test
  • Run specific tests: task test:specific -- TestName
  • Check coverage: task test:coverage
  • Verify compatibility: task test:compatibility
Getting Help

Documentation:

  • docs/AI_NAVIGATION.md - Comprehensive AI navigation guide ⭐
  • Module-specific READMEs for detailed API docs
  • docs/ directory for conceptual guides (ARCHITECTURE, ALGORITHMS, OPENSSL_COMPAT)
  • examples/ directory for working code
  • docs/COMPATIBILITY_REPORT.md for OpenSSL interoperability

Code Exploration:

  • Use task docs:serve to browse godoc locally (http://localhost:6060)
  • Check test files for usage examples
  • Review git history for context: git log -p <file>

When Stuck:

  • Understanding type system β†’ Read keypair/keypair.go:50-150 first
  • Envelope encryption issues β†’ See encryption/README.md AI Quick Start
  • OpenSSL compatibility β†’ Read docs/OPENSSL_COMPAT.md
  • Module relationships β†’ Read docs/ARCHITECTURE.md
  • Algorithm selection β†’ Read docs/ALGORITHMS.md

Critical Resources for AI Agents:

  1. docs/AI_NAVIGATION.md - Navigation paths, bug patterns, troubleshooting
  2. keypair/README.md - Foundation module with complete file map
  3. encryption/README.md - Most complex module, detailed structure
  4. docs/ARCHITECTURE.md - System design and data flows
  5. docs/OPENSSL_COMPAT.md - OpenSSL integration patterns

πŸ—οΈ Architecture

GoPKI is structured as six core modules with strong type relationships:

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚   keypair/      │◄────     cert/        │◄────   signing/      β”‚
β”‚ Core Key Mgmt   β”‚    β”‚ X.509 Certs      β”‚    β”‚ Digital Sigs    β”‚
β”‚ (75.3% coverage)β”‚    β”‚ (74.3% coverage) β”‚    β”‚ (79.8% coverage)β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
         β–²                        β–²                       β–²
         β”‚                        β”‚                       β”‚
         β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                  β–Ό                β–Ό                      β–Ό
         β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”   β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
         β”‚  encryption/    β”‚    β”‚    pkcs12/       β”‚   β”‚     jose/       β”‚
         β”‚ Data Encryption β”‚    β”‚ PKCS#12 Files    β”‚   β”‚  JWT/JWS/JWE/JWKβ”‚
         β”‚ (89.1% coverage)β”‚    β”‚ (79.1% coverage) β”‚   β”‚ (79.6% coverage)β”‚
         β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜   β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Module Documentation:

Detailed Architecture: See docs/ARCHITECTURE.md for complete system design

πŸš€ Quick Start

Generate Key Pairs
import (
    "crypto/rsa"
    "github.com/jasoet/gopki/keypair"
    "github.com/jasoet/gopki/keypair/algo"
)

// Generate RSA key pair with Manager (recommended)
manager, _ := keypair.Generate[algo.KeySize, *algo.RSAKeyPair, *rsa.PrivateKey, *rsa.PublicKey](algo.KeySize2048)

// Save with secure permissions (0600 for private, 0644 for public)
manager.SaveToPEM("private.pem", "public.pem")

// Convert to different formats
privateSSH, publicSSH, _ := manager.ToSSH("user@host", "")
privateDER, publicDER, _ := manager.ToDER()

See keypair/README.md for complete key management documentation

Create Certificates
import (
    "crypto/x509/pkix"
    "time"
    "github.com/jasoet/gopki/cert"
    "github.com/jasoet/gopki/keypair/algo"
)

// Generate key pair
keyPair, _ := algo.GenerateRSAKeyPair(algo.KeySize2048)

// Create self-signed certificate
certificate, _ := cert.CreateSelfSignedCertificate(keyPair, cert.CertificateRequest{
    Subject: pkix.Name{CommonName: "example.com"},
    DNSNames: []string{"example.com", "www.example.com"},
    ValidFor: 365 * 24 * time.Hour,
})

See cert/README.md for CA operations and certificate chains

Sign Documents
import (
    "github.com/jasoet/gopki/signing"
)

// Sign document with key pair and certificate
document := []byte("Important contract")
signature, _ := signing.SignDocument(document, keyPair, certificate)

// Verify signature
_ = signing.VerifySignature(document, signature, signing.DefaultVerifyOptions())

See signing/README.md for PKCS#7/CMS signatures and advanced options

Encrypt Data
import (
    "github.com/jasoet/gopki/encryption"
)

// Encrypt for certificate recipient
encrypted, _ := encryption.EncryptForCertificate(
    []byte("Secret message"),
    certificate.Certificate,
    encryption.DefaultEncryptOptions(),
)

// Decrypt with private key
decrypted, _ := encryption.DecryptWithKeyPair(encrypted, keyPair)

See encryption/README.md for envelope encryption and multi-recipient support

πŸ“š Examples

Comprehensive examples with complete documentation:

# Install Task runner
go install github.com/go-task/task/v3/cmd/task@latest

# Run all examples
task examples:run

# Run specific examples
task examples:keypair      # Key generation and format conversion
task examples:certificates # CA hierarchies and certificate chains
task examples:signing      # Document signing with multiple algorithms
task examples:encryption   # Data encryption with various methods

Example Documentation:

πŸ”’ Algorithm Support

Algorithm Key Sizes Key Agreement Signing Encryption Certificate
RSA 2048/3072/4096 ❌ βœ… βœ… βœ…
ECDSA P-224/256/384/521 βœ… (ECDH) βœ… βœ… βœ…
Ed25519 256-bit βœ… (X25519) βœ… βœ… (key-pair only) ⚠️

Format Support: PEM, DER, SSH, PKCS#12 (all algorithms)

See docs/ALGORITHMS.md for detailed algorithm guide and decision trees

πŸ›‘οΈ Security Features

Cryptographic Security:

  • βœ… Enforced minimum key sizes (RSA β‰₯2048 bits)
  • βœ… Secure random sources (crypto/rand.Reader only)
  • βœ… Authenticated encryption (AES-GCM)
  • βœ… Timing attack resistant (Ed25519)

File System Security:

  • βœ… Secure permissions (0600 for private keys, 0700 for directories)
  • βœ… Atomic file operations
  • βœ… Secure temporary file cleanup

Memory Security:

  • βœ… Type-safe APIs with generic constraints
  • βœ… No raw cryptographic material exposure
  • βœ… Defensive copying of sensitive parameters

πŸ§ͺ Testing

Test Coverage: 80.3% across 844+ tests

# Run comprehensive test suite
task test              # Full suite with race detection
task test:coverage     # Generate HTML coverage report
task test:compatibility # OpenSSL/OpenSSH compatibility tests

# Code quality
task lint:full         # Comprehensive linting
task lint:security     # Security-focused linting (gosec)
task format:check      # Verify code formatting

Module Coverage:

  • encryption/ 89.1% (highest)
  • keypair/algo/ 87.8%
  • signing/ 79.8%
  • pkcs12/ 79.1%
  • cert/ 74.3%
  • keypair/ 75.3%

🀝 Compatibility

OpenSSL Compatibility: 95%+

  • βœ… Certificate management (100%)
  • βœ… Digital signatures (95% - Ed25519 PKCS#7 has expected limitations)
  • βœ… Key agreement (100% - ECDH, X25519)
  • ⚠️ RSA-OAEP encryption (parameter differences)

OpenSSH Compatibility: 100%

  • βœ… SSH key format validation (all algorithms)
  • βœ… SSH fingerprint generation
  • βœ… authorized_keys format support

Compatibility Report: See docs/COMPATIBILITY_REPORT.md for detailed interoperability testing results

OpenSSL Integration Guide: See docs/OPENSSL_COMPAT.md for integration patterns

πŸ“– Standards Compliance

  • RFC 5652 - Cryptographic Message Syntax (CMS)
  • RFC 5280 - X.509 Public Key Infrastructure
  • RFC 3447 - PKCS #1: RSA Cryptography
  • RFC 7748 - Elliptic Curves (Ed25519, X25519)
  • RFC 5208 - PKCS #8: Private-Key Information
  • PKCS #7 - Cryptographic Message Syntax
  • PKCS #12 - Personal Information Exchange
  • OpenSSH - SSH public/private key formats
  • RFC 7515 - JSON Web Signature (JWS)
  • RFC 7516 - JSON Web Encryption (JWE)
  • RFC 7517 - JSON Web Key (JWK)
  • RFC 7518 - JSON Web Algorithms (JWA)
  • RFC 7519 - JSON Web Token (JWT)
  • RFC 8037 - CFRG Elliptic Curve Algorithms for JOSE

πŸ’» Development

Using Taskfile (Recommended):

task setup             # Initialize project
task test              # Run tests
task format            # Format code
task lint:full         # Comprehensive linting
task examples:run      # Run all examples
task clean             # Clean build artifacts

Manual Commands:

go test ./... -race -coverprofile=coverage.out
go build ./...
go fmt ./...
go vet ./...

Development Guide: See CLAUDE.md for comprehensive development documentation

πŸ”— Dependencies

Minimal, carefully selected dependencies:

  • go.mozilla.org/pkcs7 v0.9.0 - Battle-tested CMS/PKCS#7
  • golang.org/x/crypto v0.42.0 - Extended cryptographic primitives
  • software.sslmate.com/src/go-pkcs12 v0.6.0 - Standards-compliant PKCS#12

πŸ“„ License

MIT License - see LICENSE file for details

πŸ™ Acknowledgments

  • Mozilla for the excellent PKCS#7 library
  • Go Team for outstanding cryptographic standard library
  • Community for feedback and contributions

πŸ“ž Support

  • Documentation: Module-specific READMEs, examples, and guides
  • Issues: GitHub Issues
  • Questions: Use GitHub Issues for questions and feature requests

Made with ❀️ in Go | Type-Safe Cryptography for Production

Directories ΒΆ

Path Synopsis
bao
pki
Package pki provides integration with Vault/OpenBao PKI secrets engine.
Package pki provides integration with Vault/OpenBao PKI secrets engine.
testcontainer
Package testcontainer provides OpenBao testcontainer utilities for integration testing.
Package testcontainer provides OpenBao testcontainer utilities for integration testing.
transit
Package transit provides gopki integration for seamless key import/export with OpenBao Transit secrets engine.
Package transit provides gopki integration for seamless key import/export with OpenBao Transit secrets engine.
Package cert provides X.509 certificate creation, parsing, and management.
Package cert provides X.509 certificate creation, parsing, and management.
Package compatibility provides test helpers for verifying cryptographic interoperability with external tools like OpenSSL.
Package compatibility provides test helpers for verifying cryptographic interoperability with external tools like OpenSSL.
File cms.go implements Cryptographic Message Syntax (CMS) format support using external Mozilla PKCS7 library for reliable and standards-compliant implementation.
File cms.go implements Cryptographic Message Syntax (CMS) format support using external Mozilla PKCS7 library for reliable and standards-compliant implementation.
asymmetric
Package asymmetric provides asymmetric encryption operations using RSA, ECDSA, and Ed25519 algorithms.
Package asymmetric provides asymmetric encryption operations using RSA, ECDSA, and Ed25519 algorithms.
certificate
Package certificate provides certificate-based encryption operations that integrate with the GoPKI certificate infrastructure for document-level encryption.
Package certificate provides certificate-based encryption operations that integrate with the GoPKI certificate infrastructure for document-level encryption.
envelope
Package envelope implements hybrid envelope encryption for efficient encryption of large data sets using a combination of symmetric and asymmetric cryptography.
Package envelope implements hybrid envelope encryption for efficient encryption of large data sets using a combination of symmetric and asymmetric cryptography.
symmetric
Package symmetric provides AES-GCM symmetric encryption operations.
Package symmetric provides AES-GCM symmetric encryption operations.
examples
bao/transit/batch_operations command
Package main demonstrates batch encryption and decryption operations.
Package main demonstrates batch encryption and decryption operations.
bao/transit/gopki-integration command
Package main demonstrates how to import gopki keypairs directly into OpenBao Transit
Package main demonstrates how to import gopki keypairs directly into OpenBao Transit
bao/transit/manager-support command
Package main demonstrates using gopki Manager API with Transit
Package main demonstrates using gopki Manager API with Transit
bao/transit/signing command
Package main demonstrates digital signature operations.
Package main demonstrates digital signature operations.
bao/transit/simple_encryption command
Package main demonstrates basic encryption and decryption using the Transit client.
Package main demonstrates basic encryption and decryption using the Transit client.
internal
crypto
Package crypto provides complex cryptographic algorithms used internally by GoPKI.
Package crypto provides complex cryptographic algorithms used internally by GoPKI.
jose
internal/encoding
Package encoding provides Base64URL encoding utilities for JOSE implementations.
Package encoding provides Base64URL encoding utilities for JOSE implementations.
jwe
Package jwe provides JSON Web Encryption (JWE) support as defined in RFC 7516.
Package jwe provides JSON Web Encryption (JWE) support as defined in RFC 7516.
jwk
Package jwk provides JSON Web Key (JWK) support as defined in RFC 7517.
Package jwk provides JSON Web Key (JWK) support as defined in RFC 7517.
jws
Package jws provides JSON Web Signature (JWS) creation and verification per RFC 7515.
Package jws provides JSON Web Signature (JWS) creation and verification per RFC 7515.
jwt
Package jwt provides JSON Web Token (JWT) creation, signing, and verification per RFC 7519.
Package jwt provides JSON Web Token (JWT) creation, signing, and verification per RFC 7519.
Package keypair provides type-safe cryptographic key pair generation and management using Go generics for compile-time type safety.
Package keypair provides type-safe cryptographic key pair generation and management using Go generics for compile-time type safety.
algo
Package algo provides algorithm-specific implementations for cryptographic key pair generation.
Package algo provides algorithm-specific implementations for cryptographic key pair generation.
format
Package format defines types for cryptographic key encoding formats.
Package format defines types for cryptographic key encoding formats.
Package pkcs12 provides certificate integration utilities for PKCS#12 files.
Package pkcs12 provides certificate integration utilities for PKCS#12 files.
Package signing β€” file external.go.
Package signing β€” file external.go.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL