github.com/jasoet/gopki@v1.15.0/examples/keypair/main.go (about) 1 //go:build example 2 3 package main 4 5 import ( 6 "crypto/ecdsa" 7 "crypto/ed25519" 8 "crypto/rsa" 9 "crypto/x509/pkix" 10 "fmt" 11 "log" 12 "os" 13 "strings" 14 "time" 15 16 "github.com/jasoet/gopki/cert" 17 "github.com/jasoet/gopki/keypair" 18 "github.com/jasoet/gopki/keypair/algo" 19 "github.com/jasoet/gopki/keypair/format" 20 ) 21 22 func main() { 23 fmt.Println("=== GoPKI Keypair Module - Comprehensive Examples ===") 24 fmt.Println("Demonstrating all keypair features with type-safe APIs") 25 fmt.Println() 26 27 // Create outputs directory 28 if err := os.MkdirAll("output", 0755); err != nil { 29 log.Fatal("Failed to create output directory:", err) 30 } 31 32 // Core Examples - Algorithm-Specific Generation 33 fmt.Println("š PART 1: Algorithm-Specific Key Generation") 34 fmt.Println(strings.Repeat("=", 60)) 35 rsaAlgorithmExample() 36 ecdsaAlgorithmExample() 37 ed25519AlgorithmExample() 38 39 // Generic Manager Examples 40 fmt.Println("\nš PART 2: Generic Manager Pattern") 41 fmt.Println(strings.Repeat("=", 60)) 42 genericManagerExample() 43 managerValidationExample() 44 45 // Format Conversion Examples 46 fmt.Println("\nš PART 3: Format Conversion Matrix") 47 fmt.Println(strings.Repeat("=", 60)) 48 formatConversionExample() 49 roundTripTestingExample() 50 51 // File Operations Examples 52 fmt.Println("\nš¾ PART 4: Secure File Operations") 53 fmt.Println(strings.Repeat("=", 60)) 54 secureFileOperationsExample() 55 filePermissionsExample() 56 57 // Advanced Features 58 fmt.Println("\nš ļø PART 5: Advanced Features") 59 fmt.Println(strings.Repeat("=", 60)) 60 keyComparisonExample() 61 crossAlgorithmCompatibilityExample() 62 63 // SSH Format Support 64 fmt.Println("\nš PART 6: SSH Format Support") 65 fmt.Println(strings.Repeat("=", 60)) 66 sshFormatExample() 67 sshPassphraseExample() 68 69 // Integration Examples 70 fmt.Println("\nš PART 7: Module Integration") 71 fmt.Println(strings.Repeat("=", 60)) 72 certificateIntegrationExample() 73 typeConstraintExample() 74 75 // Performance and Security 76 fmt.Println("\nā” PART 8: Performance and Security") 77 fmt.Println(strings.Repeat("=", 60)) 78 performanceComparisonExample() 79 securityBestPracticesExample() 80 81 fmt.Println("\n" + strings.Repeat("=", 60)) 82 fmt.Println("ā All keypair examples completed successfully!") 83 fmt.Println("š Generated files are in the 'output/' directory") 84 fmt.Println("š Check file permissions with: ls -la output/") 85 fmt.Println(strings.Repeat("=", 60)) 86 } 87 88 // PART 1: Algorithm-Specific Key Generation 89 90 func rsaAlgorithmExample() { 91 fmt.Println("\n1.1 RSA Key Generation (Multiple Key Sizes)") 92 93 // Generate different RSA key sizes 94 keySizes := []algo.KeySize{algo.KeySize2048, algo.KeySize3072, algo.KeySize4096} 95 96 for _, size := range keySizes { 97 fmt.Printf(" ā Generating RSA %d-bit key pair...\n", size.Bits()) 98 99 keyPair, err := algo.GenerateRSAKeyPair(size) 100 if err != nil { 101 log.Printf("Failed to generate RSA %d-bit key: %v\n", size.Bits(), err) 102 continue 103 } 104 105 // Save to files with size in name 106 privateFile := fmt.Sprintf("output/rsa_%d_private.pem", size.Bits()) 107 publicFile := fmt.Sprintf("output/rsa_%d_public.pem", size.Bits()) 108 109 err = keypair.ToPEMFiles(keyPair, privateFile, publicFile) 110 if err != nil { 111 log.Printf("Failed to save RSA %d-bit keys: %v\n", size.Bits(), err) 112 continue 113 } 114 115 // Display key information 116 fmt.Printf(" ā Generated: %d-bit RSA key pair\n", keyPair.PrivateKey.Size()*8) 117 fmt.Printf(" ā Public key modulus size: %d bits\n", keyPair.PrivateKey.PublicKey.Size()*8) 118 fmt.Printf(" ā Files: %s, %s\n", privateFile, publicFile) 119 } 120 } 121 122 func ecdsaAlgorithmExample() { 123 fmt.Println("\n1.2 ECDSA Key Generation (All Curves)") 124 125 // Generate keys for all supported curves 126 curves := []struct { 127 curve algo.ECDSACurve 128 name string 129 }{ 130 {algo.P224, "P-224"}, 131 {algo.P256, "P-256"}, 132 {algo.P384, "P-384"}, 133 {algo.P521, "P-521"}, 134 } 135 136 for _, c := range curves { 137 fmt.Printf(" ā Generating ECDSA %s key pair...\n", c.name) 138 139 keyPair, err := algo.GenerateECDSAKeyPair(c.curve) 140 if err != nil { 141 log.Printf("Failed to generate ECDSA %s key: %v\n", c.name, err) 142 continue 143 } 144 145 // Save to files with curve in name 146 privateFile := fmt.Sprintf("output/ecdsa_%s_private.pem", strings.ToLower(c.name)) 147 publicFile := fmt.Sprintf("output/ecdsa_%s_public.pem", strings.ToLower(c.name)) 148 149 err = keypair.ToPEMFiles(keyPair, privateFile, publicFile) 150 if err != nil { 151 log.Printf("Failed to save ECDSA %s keys: %v\n", c.name, err) 152 continue 153 } 154 155 // Display key information 156 fmt.Printf(" ā Generated: ECDSA %s key pair\n", keyPair.PrivateKey.Curve.Params().Name) 157 fmt.Printf(" ā Curve bit size: %d\n", keyPair.PrivateKey.Curve.Params().BitSize) 158 fmt.Printf(" ā Files: %s, %s\n", privateFile, publicFile) 159 } 160 } 161 162 func ed25519AlgorithmExample() { 163 fmt.Println("\n1.3 Ed25519 Key Generation (High Performance)") 164 165 fmt.Printf(" ā Generating Ed25519 key pair...\n") 166 167 keyPair, err := algo.GenerateEd25519KeyPair() 168 if err != nil { 169 log.Printf("Failed to generate Ed25519 key: %v\n", err) 170 return 171 } 172 173 // Save to files 174 privateFile := "output/ed25519_private.pem" 175 publicFile := "output/ed25519_public.pem" 176 177 err = keypair.ToPEMFiles(keyPair, privateFile, publicFile) 178 if err != nil { 179 log.Printf("Failed to save Ed25519 keys: %v\n", err) 180 return 181 } 182 183 // Display key information 184 fmt.Printf(" ā Generated: Ed25519 key pair\n") 185 fmt.Printf(" ā Private key size: %d bytes\n", len(keyPair.PrivateKey)) 186 fmt.Printf(" ā Public key size: %d bytes\n", len(keyPair.PublicKey)) 187 fmt.Printf(" ā Files: %s, %s\n", privateFile, publicFile) 188 } 189 190 // PART 2: Generic Manager Pattern 191 192 func genericManagerExample() { 193 fmt.Println("\n2.1 Generic Manager Pattern with Type Safety") 194 195 // RSA Manager with full generic type specification 196 fmt.Printf(" ā Creating RSA Manager with generic constraints...\n") 197 rsaManager, err := keypair.Generate[algo.KeySize, *algo.RSAKeyPair, *rsa.PrivateKey, *rsa.PublicKey](algo.KeySize2048) 198 if err != nil { 199 log.Printf("Failed to create RSA manager: %v\n", err) 200 return 201 } 202 203 // ECDSA Manager with full generic type specification 204 fmt.Printf(" ā Creating ECDSA Manager with generic constraints...\n") 205 ecdsaManager, err := keypair.Generate[algo.ECDSACurve, *algo.ECDSAKeyPair, *ecdsa.PrivateKey, *ecdsa.PublicKey](algo.P256) 206 if err != nil { 207 log.Printf("Failed to create ECDSA manager: %v\n", err) 208 return 209 } 210 211 // Ed25519 Manager with full generic type specification 212 fmt.Printf(" ā Creating Ed25519 Manager with generic constraints...\n") 213 ed25519Manager, err := keypair.Generate[algo.Ed25519Config, *algo.Ed25519KeyPair, ed25519.PrivateKey, ed25519.PublicKey](algo.Ed25519Default) 214 if err != nil { 215 log.Printf("Failed to create Ed25519 manager: %v\n", err) 216 return 217 } 218 219 // Demonstrate Manager capabilities 220 managers := []interface{}{rsaManager, ecdsaManager, ed25519Manager} 221 names := []string{"RSA", "ECDSA", "Ed25519"} 222 223 for i, manager := range managers { 224 fmt.Printf(" ā %s Manager created successfully\n", names[i]) 225 226 // Save using Manager methods 227 filename := fmt.Sprintf("output/manager_%s.pem", strings.ToLower(names[i])) 228 229 switch m := manager.(type) { 230 case *keypair.Manager[*algo.RSAKeyPair, *rsa.PrivateKey, *rsa.PublicKey]: 231 err = m.SaveToPEM(filename, filename+".pub") 232 case *keypair.Manager[*algo.ECDSAKeyPair, *ecdsa.PrivateKey, *ecdsa.PublicKey]: 233 err = m.SaveToPEM(filename, filename+".pub") 234 case *keypair.Manager[*algo.Ed25519KeyPair, ed25519.PrivateKey, ed25519.PublicKey]: 235 err = m.SaveToPEM(filename, filename+".pub") 236 } 237 238 if err != nil { 239 log.Printf("Failed to save %s manager keys: %v\n", names[i], err) 240 continue 241 } 242 243 fmt.Printf(" ā %s Manager keys saved to: %s\n", names[i], filename) 244 } 245 } 246 247 func managerValidationExample() { 248 fmt.Println("\n2.2 Manager Validation and Information Extraction") 249 250 // Create a manager for testing 251 manager, err := keypair.Generate[algo.KeySize, *algo.RSAKeyPair, *rsa.PrivateKey, *rsa.PublicKey](algo.KeySize2048) 252 if err != nil { 253 log.Printf("Failed to create manager for validation: %v\n", err) 254 return 255 } 256 257 // Validate the manager 258 fmt.Printf(" ā Validating manager...\n") 259 260 if manager.IsValid() { 261 fmt.Printf(" ā Manager is valid and properly initialized\n") 262 } else { 263 fmt.Printf(" ā Manager validation failed\n") 264 } 265 266 // Validate private key 267 err = manager.ValidatePrivateKey() 268 if err != nil { 269 fmt.Printf(" ā Private key validation failed: %v\n", err) 270 } else { 271 fmt.Printf(" ā Private key passes security validation\n") 272 } 273 274 // Full validation 275 err = manager.Validate() 276 if err != nil { 277 fmt.Printf(" ā Full validation failed: %v\n", err) 278 } else { 279 fmt.Printf(" ā Full key pair validation successful\n") 280 } 281 282 // Extract key information 283 info, err := manager.GetInfo() 284 if err != nil { 285 log.Printf("Failed to get key info: %v\n", err) 286 return 287 } 288 fmt.Printf(" ā Key Information:\n") 289 fmt.Printf(" - Algorithm: %s\n", info.Algorithm) 290 fmt.Printf(" - Key Size: %d bits\n", info.KeySize) 291 if info.Curve != "" { 292 fmt.Printf(" - Curve: %s\n", info.Curve) 293 } 294 } 295 296 // PART 3: Format Conversion Matrix 297 298 func formatConversionExample() { 299 fmt.Println("\n3.1 Comprehensive Format Conversion Matrix") 300 301 // Generate one key of each type for format testing 302 rsaKey, _ := algo.GenerateRSAKeyPair(algo.KeySize2048) 303 ecdsaKey, _ := algo.GenerateECDSAKeyPair(algo.P256) 304 ed25519Key, _ := algo.GenerateEd25519KeyPair() 305 306 keyPairs := []struct { 307 keyPair interface{} 308 name string 309 }{ 310 {rsaKey, "RSA"}, 311 {ecdsaKey, "ECDSA"}, 312 {ed25519Key, "Ed25519"}, 313 } 314 315 for _, kp := range keyPairs { 316 fmt.Printf(" ā Converting %s key to all formats...\n", kp.name) 317 318 baseName := fmt.Sprintf("output/format_%s", strings.ToLower(kp.name)) 319 320 // Save in all formats 321 switch keyPair := kp.keyPair.(type) { 322 case *algo.RSAKeyPair: 323 // PEM format 324 keypair.ToPEMFiles(keyPair, baseName+"_private.pem", baseName+"_public.pem") 325 // DER format 326 keypair.ToDERFiles(keyPair, baseName+"_private.der", baseName+"_public.der") 327 // SSH format 328 keypair.ToSSHFiles(keyPair, baseName+"_private_ssh", baseName+"_public.ssh", "gopki@example.com", "") 329 330 case *algo.ECDSAKeyPair: 331 keypair.ToPEMFiles(keyPair, baseName+"_private.pem", baseName+"_public.pem") 332 keypair.ToDERFiles(keyPair, baseName+"_private.der", baseName+"_public.der") 333 keypair.ToSSHFiles(keyPair, baseName+"_private_ssh", baseName+"_public.ssh", "gopki@example.com", "") 334 335 case *algo.Ed25519KeyPair: 336 keypair.ToPEMFiles(keyPair, baseName+"_private.pem", baseName+"_public.pem") 337 keypair.ToDERFiles(keyPair, baseName+"_private.der", baseName+"_public.der") 338 keypair.ToSSHFiles(keyPair, baseName+"_private_ssh", baseName+"_public.ssh", "gopki@example.com", "") 339 } 340 341 fmt.Printf(" ā %s converted to: PEM, DER, SSH formats\n", kp.name) 342 343 // Calculate file sizes to show format differences 344 pemFile := baseName + "_private.pem" 345 derFile := baseName + "_private.der" 346 sshFile := baseName + "_public.ssh" 347 348 pemStat, _ := os.Stat(pemFile) 349 derStat, _ := os.Stat(derFile) 350 sshStat, _ := os.Stat(sshFile) 351 352 if pemStat != nil && derStat != nil && sshStat != nil { 353 fmt.Printf(" ā File sizes - PEM: %d, DER: %d, SSH: %d bytes\n", 354 pemStat.Size(), derStat.Size(), sshStat.Size()) 355 } 356 } 357 } 358 359 func roundTripTestingExample() { 360 fmt.Println("\n3.2 Round-Trip Format Testing (Data Integrity)") 361 362 // Generate test key 363 originalKey, err := algo.GenerateRSAKeyPair(algo.KeySize2048) 364 if err != nil { 365 log.Printf("Failed to generate test key: %v\n", err) 366 return 367 } 368 369 fmt.Printf(" ā Testing PEM round-trip...\n") 370 371 // Convert to PEM 372 pemData, err := originalKey.PrivateKeyToPEM() 373 if err != nil { 374 log.Printf("Failed to convert to PEM: %v\n", err) 375 return 376 } 377 378 // Convert back from PEM 379 reloadedKey, err := algo.RSAKeyPairFromPEM(pemData) 380 if err != nil { 381 log.Printf("Failed to reload from PEM: %v\n", err) 382 return 383 } 384 385 // Compare keys using generic manager 386 originalManager := keypair.NewManager(originalKey, originalKey.PrivateKey, &originalKey.PrivateKey.PublicKey) 387 reloadedManager := keypair.NewManager(reloadedKey, reloadedKey.PrivateKey, &reloadedKey.PrivateKey.PublicKey) 388 389 if originalManager.CompareWith(reloadedManager) { 390 fmt.Printf(" ā PEM round-trip successful - keys match perfectly\n") 391 } else { 392 fmt.Printf(" ā PEM round-trip failed - keys don't match\n") 393 } 394 395 // Test DER round-trip 396 fmt.Printf(" ā Testing DER round-trip...\n") 397 derData, err := originalKey.PrivateKeyToDER() 398 if err != nil { 399 log.Printf("Failed to convert to DER: %v\n", err) 400 return 401 } 402 403 reloadedDERKey, err := algo.RSAKeyPairFromDER(derData) 404 if err != nil { 405 log.Printf("Failed to reload from DER: %v\n", err) 406 return 407 } 408 409 reloadedDERManager := keypair.NewManager(reloadedDERKey, reloadedDERKey.PrivateKey, &reloadedDERKey.PrivateKey.PublicKey) 410 411 if originalManager.CompareWith(reloadedDERManager) { 412 fmt.Printf(" ā DER round-trip successful - keys match perfectly\n") 413 } else { 414 fmt.Printf(" ā DER round-trip failed - keys don't match\n") 415 } 416 } 417 418 // PART 4: Secure File Operations 419 420 func secureFileOperationsExample() { 421 fmt.Println("\n4.1 Secure File Operations with Proper Permissions") 422 423 // Generate key for file operations testing 424 keyPair, err := algo.GenerateRSAKeyPair(algo.KeySize2048) 425 if err != nil { 426 log.Printf("Failed to generate key for file operations: %v\n", err) 427 return 428 } 429 430 fmt.Printf(" ā Demonstrating secure file saving...\n") 431 432 // Save with secure permissions 433 privateFile := "output/secure_private.pem" 434 publicFile := "output/secure_public.pem" 435 436 err = keypair.ToPEMFiles(keyPair, privateFile, publicFile) 437 if err != nil { 438 log.Printf("Failed to save secure files: %v\n", err) 439 return 440 } 441 442 // Check file permissions 443 privateStat, err := os.Stat(privateFile) 444 if err != nil { 445 log.Printf("Failed to stat private file: %v\n", err) 446 return 447 } 448 449 publicStat, err := os.Stat(publicFile) 450 if err != nil { 451 log.Printf("Failed to stat public file: %v\n", err) 452 return 453 } 454 455 fmt.Printf(" ā Private key file permissions: %s (should be -rw-------)\n", privateStat.Mode()) 456 fmt.Printf(" ā Public key file permissions: %s\n", publicStat.Mode()) 457 fmt.Printf(" ā Files saved with secure permissions automatically\n") 458 459 // Test loading keys back 460 fmt.Printf(" ā Testing secure key loading...\n") 461 462 loadedKey, err := keypair.LoadFromPEM[*algo.RSAKeyPair, *rsa.PrivateKey, *rsa.PublicKey](privateFile) 463 if err != nil { 464 log.Printf("Failed to load key: %v\n", err) 465 return 466 } 467 468 if loadedKey.IsValid() { 469 fmt.Printf(" ā Key loaded successfully and validated\n") 470 } else { 471 fmt.Printf(" ā Loaded key failed validation\n") 472 } 473 } 474 475 func filePermissionsExample() { 476 fmt.Println("\n4.2 File Permissions Security Demonstration") 477 478 // Create a secure directory structure 479 secureDir := "output/secure" 480 if err := os.MkdirAll(secureDir, 0700); err != nil { 481 log.Printf("Failed to create secure directory: %v\n", err) 482 return 483 } 484 485 fmt.Printf(" ā Created secure directory: %s (permissions: 0700)\n", secureDir) 486 487 // Check directory permissions 488 dirStat, err := os.Stat(secureDir) 489 if err != nil { 490 log.Printf("Failed to stat secure directory: %v\n", err) 491 return 492 } 493 494 fmt.Printf(" ā Directory permissions: %s (owner access only)\n", dirStat.Mode()) 495 496 // Generate and save keys in secure directory 497 keyPair, err := algo.GenerateECDSAKeyPair(algo.P256) 498 if err != nil { 499 log.Printf("Failed to generate key: %v\n", err) 500 return 501 } 502 503 securePrivateFile := secureDir + "/ecdsa_private.pem" 504 securePublicFile := secureDir + "/ecdsa_public.pem" 505 506 err = keypair.ToPEMFiles(keyPair, securePrivateFile, securePublicFile) 507 if err != nil { 508 log.Printf("Failed to save keys in secure directory: %v\n", err) 509 return 510 } 511 512 fmt.Printf(" ā Keys saved in secure directory structure\n") 513 fmt.Printf(" ā Private key: %s\n", securePrivateFile) 514 fmt.Printf(" ā Public key: %s\n", securePublicFile) 515 } 516 517 // PART 5: Advanced Features 518 519 func keyComparisonExample() { 520 fmt.Println("\n5.1 Key Comparison and Validation Operations") 521 522 // Generate two identical key managers for comparison 523 key1, _ := algo.GenerateRSAKeyPair(algo.KeySize2048) 524 key2, _ := algo.GenerateRSAKeyPair(algo.KeySize2048) 525 526 manager1 := keypair.NewManager(key1, key1.PrivateKey, &key1.PrivateKey.PublicKey) 527 manager2 := keypair.NewManager(key2, key2.PrivateKey, &key2.PrivateKey.PublicKey) 528 529 fmt.Printf(" ā Comparing different key pairs...\n") 530 531 // Compare different keys 532 if manager1.CompareWith(manager2) { 533 fmt.Printf(" ā Different keys reported as same (this should not happen)\n") 534 } else { 535 fmt.Printf(" ā Different keys correctly identified as different\n") 536 } 537 538 // Compare same key with itself 539 if manager1.CompareWith(manager1) { 540 fmt.Printf(" ā Same key correctly identified as identical\n") 541 } else { 542 fmt.Printf(" ā Same key reported as different (this should not happen)\n") 543 } 544 545 // Test private key comparison 546 fmt.Printf(" ā Testing private key comparison...\n") 547 if manager1.ComparePrivateKeys(manager2) { 548 fmt.Printf(" ā Different private keys reported as same\n") 549 } else { 550 fmt.Printf(" ā Different private keys correctly identified\n") 551 } 552 553 // Test public key comparison 554 fmt.Printf(" ā Testing public key comparison...\n") 555 if manager1.ComparePublicKeys(manager2) { 556 fmt.Printf(" ā Different public keys reported as same\n") 557 } else { 558 fmt.Printf(" ā Different public keys correctly identified\n") 559 } 560 } 561 562 func crossAlgorithmCompatibilityExample() { 563 fmt.Println("\n5.2 Cross-Algorithm Compatibility Testing") 564 565 // Generate keys of different algorithms 566 rsaKey, _ := algo.GenerateRSAKeyPair(algo.KeySize2048) 567 ecdsaKey, _ := algo.GenerateECDSAKeyPair(algo.P256) 568 ed25519Key, _ := algo.GenerateEd25519KeyPair() 569 570 keyPairs := []struct { 571 keyPair interface{} 572 name string 573 }{ 574 {rsaKey, "RSA-2048"}, 575 {ecdsaKey, "ECDSA-P256"}, 576 {ed25519Key, "Ed25519"}, 577 } 578 579 fmt.Printf(" ā Testing format compatibility across algorithms...\n") 580 581 for _, kp := range keyPairs { 582 // Test PEM format with each algorithm 583 switch keyPair := kp.keyPair.(type) { 584 case *algo.RSAKeyPair: 585 pemData, err := keyPair.PrivateKeyToPEM() 586 if err != nil { 587 fmt.Printf(" ā %s PEM conversion failed: %v\n", kp.name, err) 588 continue 589 } 590 591 // Try to reload 592 _, err = algo.RSAKeyPairFromPEM(pemData) 593 if err != nil { 594 fmt.Printf(" ā %s PEM reload failed: %v\n", kp.name, err) 595 } else { 596 fmt.Printf(" ā %s PEM round-trip successful\n", kp.name) 597 } 598 599 case *algo.ECDSAKeyPair: 600 pemData, err := keyPair.PrivateKeyToPEM() 601 if err != nil { 602 fmt.Printf(" ā %s PEM conversion failed: %v\n", kp.name, err) 603 continue 604 } 605 606 _, err = algo.ECDSAKeyPairFromPEM(pemData) 607 if err != nil { 608 fmt.Printf(" ā %s PEM reload failed: %v\n", kp.name, err) 609 } else { 610 fmt.Printf(" ā %s PEM round-trip successful\n", kp.name) 611 } 612 613 case *algo.Ed25519KeyPair: 614 pemData, err := keyPair.PrivateKeyToPEM() 615 if err != nil { 616 fmt.Printf(" ā %s PEM conversion failed: %v\n", kp.name, err) 617 continue 618 } 619 620 _, err = algo.Ed25519KeyPairFromPEM(pemData) 621 if err != nil { 622 fmt.Printf(" ā %s PEM reload failed: %v\n", kp.name, err) 623 } else { 624 fmt.Printf(" ā %s PEM round-trip successful\n", kp.name) 625 } 626 } 627 } 628 } 629 630 // PART 6: SSH Format Support 631 632 func sshFormatExample() { 633 fmt.Println("\n6.1 SSH Format Support (OpenSSH Compatible)") 634 635 // Generate keys for SSH format testing 636 algorithms := []struct { 637 generateKey func() (interface{}, error) 638 name string 639 }{ 640 {func() (interface{}, error) { return algo.GenerateRSAKeyPair(algo.KeySize2048) }, "RSA"}, 641 {func() (interface{}, error) { return algo.GenerateECDSAKeyPair(algo.P256) }, "ECDSA"}, 642 {func() (interface{}, error) { return algo.GenerateEd25519KeyPair() }, "Ed25519"}, 643 } 644 645 for _, alg := range algorithms { 646 fmt.Printf(" ā Testing %s SSH format...\n", alg.name) 647 648 keyPair, err := alg.generateKey() 649 if err != nil { 650 log.Printf("Failed to generate %s key: %v\n", alg.name, err) 651 continue 652 } 653 654 comment := fmt.Sprintf("gopki-%s@example.com", strings.ToLower(alg.name)) 655 sshPrivateFile := fmt.Sprintf("output/ssh_%s_id", strings.ToLower(alg.name)) 656 sshPublicFile := fmt.Sprintf("output/ssh_%s_id.pub", strings.ToLower(alg.name)) 657 658 // Convert to SSH format 659 switch kp := keyPair.(type) { 660 case *algo.RSAKeyPair: 661 err = keypair.ToSSHFiles(kp, sshPrivateFile, sshPublicFile, comment, "") 662 case *algo.ECDSAKeyPair: 663 err = keypair.ToSSHFiles(kp, sshPrivateFile, sshPublicFile, comment, "") 664 case *algo.Ed25519KeyPair: 665 err = keypair.ToSSHFiles(kp, sshPrivateFile, sshPublicFile, comment, "") 666 } 667 668 if err != nil { 669 log.Printf("Failed to save %s SSH keys: %v\n", alg.name, err) 670 continue 671 } 672 673 // Read and display SSH public key format 674 sshPublicData, err := os.ReadFile(sshPublicFile) 675 if err != nil { 676 log.Printf("Failed to read SSH public key: %v\n", err) 677 continue 678 } 679 680 fmt.Printf(" ā %s SSH keys generated\n", alg.name) 681 fmt.Printf(" ā SSH public key: %s\n", strings.TrimSpace(string(sshPublicData))) 682 fmt.Printf(" ā Compatible with ~/.ssh/authorized_keys\n") 683 684 // Test loading SSH private key back 685 switch keyPairTyped := keyPair.(type) { 686 case *algo.RSAKeyPair: 687 sshData, _ := os.ReadFile(sshPrivateFile) 688 _, err = algo.RSAKeyPairFromSSH(format.SSH(sshData), "") 689 case *algo.ECDSAKeyPair: 690 sshData, _ := os.ReadFile(sshPrivateFile) 691 _, err = algo.ECDSAKeyPairFromSSH(format.SSH(sshData), "") 692 case *algo.Ed25519KeyPair: 693 sshData, _ := os.ReadFile(sshPrivateFile) 694 _ = keyPairTyped // use the variable 695 _, err = algo.Ed25519KeyPairFromSSH(format.SSH(sshData), "") 696 } 697 698 if err != nil { 699 fmt.Printf(" ā SSH private key reload failed: %v\n", err) 700 } else { 701 fmt.Printf(" ā SSH private key reload successful\n") 702 } 703 } 704 } 705 706 func sshPassphraseExample() { 707 fmt.Println("\n6.2 SSH Format with Passphrase Protection") 708 709 // Generate key for passphrase testing 710 keyPair, err := algo.GenerateRSAKeyPair(algo.KeySize2048) 711 if err != nil { 712 log.Printf("Failed to generate key for passphrase test: %v\n", err) 713 return 714 } 715 716 fmt.Printf(" ā Testing SSH format with passphrase protection...\n") 717 718 passphrase := "secure-passphrase-123" 719 comment := "gopki-protected@example.com" 720 721 // Save with passphrase 722 protectedPrivate := "output/ssh_protected_id" 723 protectedPublic := "output/ssh_protected_id.pub" 724 725 err = keypair.ToSSHFiles(keyPair, protectedPrivate, protectedPublic, comment, passphrase) 726 if err != nil { 727 log.Printf("Failed to save passphrase-protected SSH key: %v\n", err) 728 return 729 } 730 731 fmt.Printf(" ā SSH key saved with passphrase protection\n") 732 733 // Try to load without passphrase (should fail) 734 sshData, _ := os.ReadFile(protectedPrivate) 735 _, err = algo.RSAKeyPairFromSSH(format.SSH(sshData), "") 736 if err != nil { 737 fmt.Printf(" ā Protected key correctly rejects empty passphrase\n") 738 } else { 739 fmt.Printf(" ā Protected key should have rejected empty passphrase\n") 740 } 741 742 // Load with correct passphrase 743 _, err = algo.RSAKeyPairFromSSH(format.SSH(sshData), passphrase) 744 if err != nil { 745 fmt.Printf(" ā Failed to load with correct passphrase: %v\n", err) 746 } else { 747 fmt.Printf(" ā Protected key loaded successfully with correct passphrase\n") 748 } 749 750 // Try wrong passphrase (should fail) 751 _, err = algo.RSAKeyPairFromSSH(format.SSH(sshData), "wrong-passphrase") 752 if err != nil { 753 fmt.Printf(" ā Protected key correctly rejects wrong passphrase\n") 754 } else { 755 fmt.Printf(" ā Protected key should have rejected wrong passphrase\n") 756 } 757 } 758 759 // PART 7: Module Integration 760 761 func certificateIntegrationExample() { 762 fmt.Println("\n7.1 Certificate Module Integration") 763 764 // Generate key pairs for certificate creation 765 algorithms := []struct { 766 generateKey func() (interface{}, error) 767 name string 768 }{ 769 {func() (interface{}, error) { return algo.GenerateRSAKeyPair(algo.KeySize2048) }, "RSA"}, 770 {func() (interface{}, error) { return algo.GenerateECDSAKeyPair(algo.P256) }, "ECDSA"}, 771 {func() (interface{}, error) { return algo.GenerateEd25519KeyPair() }, "Ed25519"}, 772 } 773 774 for _, alg := range algorithms { 775 fmt.Printf(" ā Creating certificate with %s key...\n", alg.name) 776 777 keyPair, err := alg.generateKey() 778 if err != nil { 779 log.Printf("Failed to generate %s key: %v\n", alg.name, err) 780 continue 781 } 782 783 // Create certificate request 784 certRequest := cert.CertificateRequest{ 785 Subject: pkix.Name{ 786 CommonName: fmt.Sprintf("%s Test Certificate", alg.name), 787 Organization: []string{"GoPKI Examples"}, 788 Country: []string{"US"}, 789 }, 790 DNSNames: []string{fmt.Sprintf("%s.example.com", strings.ToLower(alg.name))}, 791 ValidFor: 365 * 24 * time.Hour, 792 } 793 794 // Create self-signed certificate using the key pair 795 var certificate *cert.Certificate 796 switch kp := keyPair.(type) { 797 case *algo.RSAKeyPair: 798 certificate, err = cert.CreateSelfSignedCertificate(kp, certRequest) 799 case *algo.ECDSAKeyPair: 800 certificate, err = cert.CreateSelfSignedCertificate(kp, certRequest) 801 case *algo.Ed25519KeyPair: 802 certificate, err = cert.CreateSelfSignedCertificate(kp, certRequest) 803 } 804 805 if err != nil { 806 log.Printf("Failed to create %s certificate: %v\n", alg.name, err) 807 continue 808 } 809 810 // Save certificate 811 certFile := fmt.Sprintf("output/cert_%s.pem", strings.ToLower(alg.name)) 812 err = certificate.SaveToFile(certFile) 813 if err != nil { 814 log.Printf("Failed to save %s certificate: %v\n", alg.name, err) 815 continue 816 } 817 818 fmt.Printf(" ā %s certificate created successfully\n", alg.name) 819 fmt.Printf(" ā Subject: %s\n", certificate.Certificate.Subject.CommonName) 820 fmt.Printf(" ā Valid from: %s\n", certificate.Certificate.NotBefore.Format("2006-01-02")) 821 fmt.Printf(" ā Valid until: %s\n", certificate.Certificate.NotAfter.Format("2006-01-02")) 822 fmt.Printf(" ā Certificate file: %s\n", certFile) 823 } 824 } 825 826 func typeConstraintExample() { 827 fmt.Println("\n7.2 Type Constraint System Demonstration") 828 829 fmt.Printf(" ā Demonstrating compile-time type safety...\n") 830 831 // This demonstrates how the generic type system prevents runtime errors 832 // by catching type mismatches at compile time 833 834 // RSA key with proper type constraints 835 rsaKey, err := algo.GenerateRSAKeyPair(algo.KeySize2048) 836 if err != nil { 837 log.Printf("Failed to generate RSA key: %v\n", err) 838 return 839 } 840 841 // Generic function that works with any private key type 842 privateKeyToPEM := func(key interface{}) (format.PEM, error) { 843 switch k := key.(type) { 844 case *rsa.PrivateKey: 845 return keypair.PrivateKeyToPEM(k) 846 case *ecdsa.PrivateKey: 847 return keypair.PrivateKeyToPEM(k) 848 case ed25519.PrivateKey: 849 return keypair.PrivateKeyToPEM(k) 850 default: 851 return nil, fmt.Errorf("unsupported private key type") 852 } 853 } 854 855 // Test with RSA private key 856 pemData, err := privateKeyToPEM(rsaKey.PrivateKey) 857 if err != nil { 858 log.Printf("Failed to convert RSA private key to PEM: %v\n", err) 859 return 860 } 861 862 fmt.Printf(" ā Type-safe conversion successful\n") 863 fmt.Printf(" ā RSA private key converted to PEM (%d bytes)\n", len(pemData)) 864 865 // Demonstrate type constraint validation 866 info := keypair.KeyInfo{ 867 Algorithm: "RSA", 868 KeySize: 2048, 869 Curve: "", 870 } 871 872 fmt.Printf(" ā Type constraints enforce security:\n") 873 fmt.Printf(" - Algorithm: %s\n", info.Algorithm) 874 fmt.Printf(" - Key Size: %d bits (ā„2048 required)\n", info.KeySize) 875 fmt.Printf(" - Type safety prevents runtime errors\n") 876 } 877 878 // PART 8: Performance and Security 879 880 func performanceComparisonExample() { 881 fmt.Println("\n8.1 Algorithm Performance Comparison") 882 883 // Measure key generation performance for each algorithm 884 algorithms := []struct { 885 name string 886 generate func() (interface{}, error) 887 keySize string 888 }{ 889 {"RSA-2048", func() (interface{}, error) { return algo.GenerateRSAKeyPair(algo.KeySize2048) }, "2048 bits"}, 890 {"RSA-3072", func() (interface{}, error) { return algo.GenerateRSAKeyPair(algo.KeySize3072) }, "3072 bits"}, 891 {"ECDSA-P256", func() (interface{}, error) { return algo.GenerateECDSAKeyPair(algo.P256) }, "256 bits"}, 892 {"ECDSA-P384", func() (interface{}, error) { return algo.GenerateECDSAKeyPair(algo.P384) }, "384 bits"}, 893 {"Ed25519", func() (interface{}, error) { return algo.GenerateEd25519KeyPair() }, "256 bits"}, 894 } 895 896 fmt.Printf(" ā Measuring key generation performance...\n") 897 fmt.Printf(" %-12s %-12s %-12s %s\n", "Algorithm", "Key Size", "Gen Time", "Status") 898 fmt.Printf(" %s\n", strings.Repeat("-", 60)) 899 900 for _, alg := range algorithms { 901 start := time.Now() 902 903 keyPair, err := alg.generate() 904 905 duration := time.Since(start) 906 907 if err != nil { 908 fmt.Printf(" %-12s %-12s %-12s %s\n", alg.name, alg.keySize, "ERROR", err.Error()) 909 continue 910 } 911 912 // Verify key was generated successfully 913 var status string = "ā Success" 914 switch kp := keyPair.(type) { 915 case *algo.RSAKeyPair: 916 if kp.PrivateKey == nil { 917 status = "ā Failed" 918 } 919 case *algo.ECDSAKeyPair: 920 if kp.PrivateKey == nil { 921 status = "ā Failed" 922 } 923 case *algo.Ed25519KeyPair: 924 if len(kp.PrivateKey) == 0 { 925 status = "ā Failed" 926 } 927 } 928 929 fmt.Printf(" %-12s %-12s %-12s %s\n", 930 alg.name, alg.keySize, fmt.Sprintf("%.2fms", float64(duration.Microseconds())/1000.0), status) 931 } 932 933 fmt.Printf("\n ā Performance Notes:\n") 934 fmt.Printf(" ⢠Ed25519: Fastest generation and signing\n") 935 fmt.Printf(" ⢠ECDSA: Good balance of security and performance\n") 936 fmt.Printf(" ⢠RSA: Slower but widely supported\n") 937 } 938 939 func securityBestPracticesExample() { 940 fmt.Println("\n8.2 Security Best Practices Demonstration") 941 942 fmt.Printf(" ā Demonstrating security best practices...\n") 943 944 // 1. Minimum key size enforcement 945 fmt.Printf(" 1. Minimum RSA key size enforcement:\n") 946 947 // This would fail at compile time with proper key size constants 948 validKeySizes := []algo.KeySize{algo.KeySize2048, algo.KeySize3072, algo.KeySize4096} 949 for _, size := range validKeySizes { 950 _, err := algo.GenerateRSAKeyPair(size) 951 if err != nil { 952 fmt.Printf(" ā %d-bit RSA rejected: %v\n", size.Bits(), err) 953 } else { 954 fmt.Printf(" ā %d-bit RSA accepted (ā„2048 required)\n", size.Bits()) 955 } 956 } 957 958 // 2. Secure random number generation 959 fmt.Printf(" 2. Cryptographically secure random generation:\n") 960 testKey, err := algo.GenerateECDSAKeyPair(algo.P256) 961 if err != nil { 962 log.Printf("Failed to generate key for randomness test: %v\n", err) 963 return 964 } 965 _ = testKey // use the variable to avoid unused error 966 967 // Generate multiple keys to show randomness 968 keys := make([]*algo.ECDSAKeyPair, 3) 969 for i := 0; i < 3; i++ { 970 keys[i], _ = algo.GenerateECDSAKeyPair(algo.P256) 971 } 972 973 // Compare X coordinates to show they're different (random) 974 allDifferent := true 975 for i := 0; i < len(keys)-1; i++ { 976 for j := i + 1; j < len(keys); j++ { 977 if keys[i].PrivateKey.X.Cmp(keys[j].PrivateKey.X) == 0 { 978 allDifferent = false 979 break 980 } 981 } 982 if !allDifferent { 983 break 984 } 985 } 986 987 if allDifferent { 988 fmt.Printf(" ā All generated keys are cryptographically unique\n") 989 } else { 990 fmt.Printf(" ā Key generation may have randomness issues\n") 991 } 992 993 // 3. Secure file permissions 994 fmt.Printf(" 3. Secure file permission enforcement:\n") 995 testRSAKey, _ := algo.GenerateRSAKeyPair(algo.KeySize2048) 996 testFile := "output/security_test_private.pem" 997 998 err = keypair.ToPEMFiles(testRSAKey, testFile, testFile+".pub") 999 if err != nil { 1000 log.Printf("Failed to save security test key: %v\n", err) 1001 return 1002 } 1003 1004 stat, err := os.Stat(testFile) 1005 if err != nil { 1006 log.Printf("Failed to stat security test file: %v\n", err) 1007 return 1008 } 1009 1010 perm := stat.Mode().Perm() 1011 if perm == 0600 { 1012 fmt.Printf(" ā Private key saved with 0600 permissions (owner only)\n") 1013 } else { 1014 fmt.Printf(" ā ļø Private key permissions: %o (should be 0600)\n", perm) 1015 } 1016 1017 // 4. Type safety prevents errors 1018 fmt.Printf(" 4. Compile-time type safety:\n") 1019 fmt.Printf(" ā Generic constraints prevent key type mismatches\n") 1020 fmt.Printf(" ā Algorithm-specific types ensure correct usage\n") 1021 fmt.Printf(" ā Format types prevent data corruption\n") 1022 1023 fmt.Printf(" Security Best Practices Summary:\n") 1024 fmt.Printf(" ⢠Use RSA ā„2048 bits (enforced at compile time)\n") 1025 fmt.Printf(" ⢠ECDSA P-256+ or Ed25519 for modern applications\n") 1026 fmt.Printf(" ⢠Private keys automatically saved with 0600 permissions\n") 1027 fmt.Printf(" ⢠SSH keys support passphrase protection\n") 1028 fmt.Printf(" ⢠Type-safe APIs prevent common programming errors\n") 1029 }