github.com/jasoet/gopki@v1.15.0/pkcs12/cert_integration_test.go (about) 1 package pkcs12 2 3 import ( 4 "crypto/rand" 5 "crypto/rsa" 6 "crypto/x509" 7 "crypto/x509/pkix" 8 "encoding/pem" 9 "math/big" 10 "net" 11 "os" 12 "path/filepath" 13 "testing" 14 "time" 15 16 "github.com/jasoet/gopki/cert" 17 "github.com/jasoet/gopki/keypair/algo" 18 ) 19 20 func TestCertIntegrationComprehensive(t *testing.T) { 21 tempDir := t.TempDir() 22 23 // Generate test key pair and certificate for use in tests 24 privateKey, err := rsa.GenerateKey(rand.Reader, 2048) 25 if err != nil { 26 t.Fatalf("Failed to generate RSA keys: %v", err) 27 } 28 29 template := &x509.Certificate{ 30 Subject: pkix.Name{ 31 CommonName: "Test Certificate", 32 Organization: []string{"Test Org"}, 33 Country: []string{"US"}, 34 }, 35 NotBefore: time.Now(), 36 NotAfter: time.Now().Add(365 * 24 * time.Hour), 37 KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment, 38 ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageClientAuth}, 39 SerialNumber: big.NewInt(1), 40 DNSNames: []string{"localhost", "test.example.com"}, 41 IPAddresses: []net.IP{net.IPv4(127, 0, 0, 1)}, 42 } 43 44 certDER, err := x509.CreateCertificate(rand.Reader, template, template, &privateKey.PublicKey, privateKey) 45 if err != nil { 46 t.Fatalf("Failed to create certificate: %v", err) 47 } 48 49 certificate, err := x509.ParseCertificate(certDER) 50 if err != nil { 51 t.Fatalf("Failed to parse certificate: %v", err) 52 } 53 54 // Create a CA certificate for chain testing 55 caTemplate := &x509.Certificate{ 56 Subject: pkix.Name{ 57 CommonName: "Test CA", 58 Organization: []string{"Test CA Org"}, 59 Country: []string{"US"}, 60 }, 61 NotBefore: time.Now(), 62 NotAfter: time.Now().Add(10 * 365 * 24 * time.Hour), 63 KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign, 64 IsCA: true, 65 SerialNumber: big.NewInt(100), 66 BasicConstraintsValid: true, 67 } 68 69 caPrivateKey, err := rsa.GenerateKey(rand.Reader, 2048) 70 if err != nil { 71 t.Fatalf("Failed to generate CA keys: %v", err) 72 } 73 74 caCertDER, err := x509.CreateCertificate(rand.Reader, caTemplate, caTemplate, &caPrivateKey.PublicKey, caPrivateKey) 75 if err != nil { 76 t.Fatalf("Failed to create CA certificate: %v", err) 77 } 78 79 caCertificate, err := x509.ParseCertificate(caCertDER) 80 if err != nil { 81 t.Fatalf("Failed to parse CA certificate: %v", err) 82 } 83 84 t.Run("FromP12Cert", func(t *testing.T) { 85 // Create P12 data 86 opts := DefaultCreateOptions("test123") 87 p12Data, err := CreateP12(privateKey, certificate, nil, opts) 88 if err != nil { 89 t.Fatalf("Failed to create P12 data: %v", err) 90 } 91 92 // Test loading certificate from P12 data 93 goPKICert, caCerts, err := FromP12Cert(p12Data, "test123") 94 if err != nil { 95 t.Errorf("FromP12Cert failed: %v", err) 96 } 97 if goPKICert == nil { 98 t.Error("Expected non-nil GoPKI certificate") 99 } 100 if goPKICert.Certificate.Subject.CommonName != "Test Certificate" { 101 t.Error("Certificate subject mismatch") 102 } 103 if len(caCerts) != 0 { 104 t.Error("Expected no CA certificates in basic test") 105 } 106 107 // Test error cases 108 _, _, err = FromP12Cert(nil, "test123") 109 if err == nil { 110 t.Error("Expected error for nil P12 data") 111 } 112 113 _, _, err = FromP12Cert(p12Data, "") 114 if err == nil { 115 t.Error("Expected error for empty password") 116 } 117 118 _, _, err = FromP12Cert([]byte("invalid"), "test123") 119 if err == nil { 120 t.Error("Expected error for invalid P12 data") 121 } 122 }) 123 124 t.Run("FromP12CertFile", func(t *testing.T) { 125 // Create P12 file 126 p12File := filepath.Join(tempDir, "test_cert.p12") 127 opts := DefaultCreateOptions("test123") 128 err := CreateP12File(p12File, privateKey, certificate, nil, opts) 129 if err != nil { 130 t.Fatalf("Failed to create P12 file: %v", err) 131 } 132 133 // Test loading certificate from P12 file 134 goPKICert, _, err := FromP12CertFile(p12File, "test123") 135 if err != nil { 136 t.Errorf("FromP12CertFile failed: %v", err) 137 } 138 if goPKICert == nil { 139 t.Error("Expected non-nil GoPKI certificate") 140 } 141 if goPKICert.Certificate.Subject.CommonName != "Test Certificate" { 142 t.Error("Certificate subject mismatch") 143 } 144 145 // Test error cases 146 _, _, err = FromP12CertFile("", "test123") 147 if err == nil { 148 t.Error("Expected error for empty filename") 149 } 150 151 _, _, err = FromP12CertFile("nonexistent.p12", "test123") 152 if err == nil { 153 t.Error("Expected error for nonexistent file") 154 } 155 }) 156 157 t.Run("LoadCertificateChainFromP12", func(t *testing.T) { 158 // Create P12 file with certificate chain 159 caCerts := []*x509.Certificate{caCertificate} 160 opts := DefaultCreateOptions("test123") 161 p12File := filepath.Join(tempDir, "chain_test.p12") 162 err := CreateP12File(p12File, privateKey, certificate, caCerts, opts) 163 if err != nil { 164 t.Fatalf("Failed to create P12 file with chain: %v", err) 165 } 166 167 // Test loading certificate chain 168 certificates, err := LoadCertificateChainFromP12(p12File, "test123") 169 if err != nil { 170 t.Errorf("LoadCertificateChainFromP12 failed: %v", err) 171 } 172 if len(certificates) < 1 { 173 t.Error("Expected at least one certificate") 174 } 175 if certificates[0].Certificate.Subject.CommonName != "Test Certificate" { 176 t.Error("First certificate subject mismatch") 177 } 178 179 // Test error cases 180 _, err = LoadCertificateChainFromP12("", "test123") 181 if err == nil { 182 t.Error("Expected error for empty filename") 183 } 184 185 _, err = LoadCertificateChainFromP12("nonexistent.p12", "test123") 186 if err == nil { 187 t.Error("Expected error for nonexistent file") 188 } 189 }) 190 191 t.Run("SaveCertToP12", func(t *testing.T) { 192 // Wrap certificate in GoPKI Certificate 193 goPKICert := &cert.Certificate{ 194 Certificate: certificate, 195 } 196 197 // Test saving certificate to P12 file 198 p12File := filepath.Join(tempDir, "save_test.p12") 199 err := SaveCertToP12(goPKICert, privateKey, p12File, "test123") 200 if err != nil { 201 t.Errorf("SaveCertToP12 failed: %v", err) 202 } 203 204 // Verify file was created 205 if _, err := os.Stat(p12File); os.IsNotExist(err) { 206 t.Error("P12 file was not created") 207 } 208 209 // Verify by loading it back 210 loadedContainer, err := QuickLoadP12(p12File, "test123") 211 if err != nil { 212 t.Errorf("Failed to load saved P12 file: %v", err) 213 } 214 if loadedContainer.Certificate.Subject.CommonName != "Test Certificate" { 215 t.Error("Round-trip certificate subject mismatch") 216 } 217 218 // Test error cases 219 err = SaveCertToP12(nil, privateKey, p12File, "test123") 220 if err == nil { 221 t.Error("Expected error for nil certificate") 222 } 223 224 err = SaveCertToP12(goPKICert, nil, p12File, "test123") 225 if err == nil { 226 t.Error("Expected error for nil private key") 227 } 228 }) 229 230 t.Run("SaveCertToP12WithChain", func(t *testing.T) { 231 // Wrap certificate in GoPKI Certificate 232 goPKICert := &cert.Certificate{ 233 Certificate: certificate, 234 } 235 236 // Wrap CA certificates in GoPKI certificates 237 goPKICACerts := []*cert.Certificate{ 238 {Certificate: caCertificate}, 239 } 240 241 // Test saving certificate with chain to P12 file 242 p12File := filepath.Join(tempDir, "save_chain_test.p12") 243 err := SaveCertToP12WithChain(goPKICert, privateKey, goPKICACerts, p12File, "test123") 244 if err != nil { 245 t.Errorf("SaveCertToP12WithChain failed: %v", err) 246 } 247 248 // Verify file was created 249 if _, err := os.Stat(p12File); os.IsNotExist(err) { 250 t.Error("P12 file was not created") 251 } 252 253 // Verify by loading it back 254 loadedContainer, err := QuickLoadP12(p12File, "test123") 255 if err != nil { 256 t.Errorf("Failed to load saved P12 file with chain: %v", err) 257 } 258 if len(loadedContainer.CACertificates) != 1 { 259 t.Errorf("Expected 1 CA certificate, got %d", len(loadedContainer.CACertificates)) 260 } 261 262 // Test error cases 263 err = SaveCertToP12WithChain(nil, privateKey, goPKICACerts, p12File, "test123") 264 if err == nil { 265 t.Error("Expected error for nil certificate") 266 } 267 }) 268 269 t.Run("ExtractCertificatesFromP12", func(t *testing.T) { 270 // Create P12 with certificate chain 271 caCerts := []*x509.Certificate{caCertificate} 272 opts := DefaultCreateOptions("test123") 273 p12File := filepath.Join(tempDir, "extract_test.p12") 274 err := CreateP12File(p12File, privateKey, certificate, caCerts, opts) 275 if err != nil { 276 t.Fatalf("Failed to create P12 file: %v", err) 277 } 278 279 // Test extracting all certificates to output directory 280 outputDir := filepath.Join(tempDir, "extracted_certs") 281 err = ExtractCertificatesFromP12(p12File, "test123", outputDir) 282 if err != nil { 283 t.Errorf("ExtractCertificatesFromP12 failed: %v", err) 284 } 285 286 // Verify output directory was created and contains certificate files 287 if _, err := os.Stat(outputDir); os.IsNotExist(err) { 288 t.Error("Output directory was not created") 289 } 290 291 // Test error cases 292 err = ExtractCertificatesFromP12("", "test123", outputDir) 293 if err == nil { 294 t.Error("Expected error for empty filename") 295 } 296 297 err = ExtractCertificatesFromP12("nonexistent.p12", "test123", outputDir) 298 if err == nil { 299 t.Error("Expected error for nonexistent file") 300 } 301 }) 302 303 t.Run("ValidateP12Certificate", func(t *testing.T) { 304 // Create P12 file 305 p12File := filepath.Join(tempDir, "validate_test.p12") 306 opts := DefaultCreateOptions("test123") 307 err := CreateP12File(p12File, privateKey, certificate, nil, opts) 308 if err != nil { 309 t.Fatalf("Failed to create P12 file: %v", err) 310 } 311 312 // Test validation 313 validationResult, err := ValidateP12Certificate(p12File, "test123") 314 if err != nil { 315 t.Errorf("ValidateP12Certificate failed: %v", err) 316 } 317 if validationResult == nil { 318 t.Error("Expected non-nil validation result") 319 } 320 321 // Test error cases 322 _, err = ValidateP12Certificate("", "test123") 323 if err == nil { 324 t.Error("Expected error for empty filename") 325 } 326 327 _, err = ValidateP12Certificate("nonexistent.p12", "test123") 328 if err == nil { 329 t.Error("Expected error for nonexistent file") 330 } 331 }) 332 333 t.Run("ImportP12AndSavePEM", func(t *testing.T) { 334 // Create P12 file 335 p12File := filepath.Join(tempDir, "import_test.p12") 336 opts := DefaultCreateOptions("test123") 337 err := CreateP12File(p12File, privateKey, certificate, nil, opts) 338 if err != nil { 339 t.Fatalf("Failed to create P12 file: %v", err) 340 } 341 342 // Test importing and saving as PEM 343 pemFile := filepath.Join(tempDir, "imported.pem") 344 err = ImportP12AndSavePEM(p12File, "test123", pemFile) 345 if err != nil { 346 t.Errorf("ImportP12AndSavePEM failed: %v", err) 347 } 348 349 // Verify PEM file was created 350 if _, err := os.Stat(pemFile); os.IsNotExist(err) { 351 t.Error("PEM file was not created") 352 } 353 354 // Test error cases 355 err = ImportP12AndSavePEM("", "test123", pemFile) 356 if err == nil { 357 t.Error("Expected error for empty P12 filename") 358 } 359 }) 360 361 t.Run("CreateP12FromPEM", func(t *testing.T) { 362 // First create PEM files 363 certPEMFile := filepath.Join(tempDir, "cert.pem") 364 keyPEMFile := filepath.Join(tempDir, "key.pem") 365 366 // Save certificate to PEM 367 certPEM := &pem.Block{ 368 Type: "CERTIFICATE", 369 Bytes: certificate.Raw, 370 } 371 certFile, err := os.Create(certPEMFile) 372 if err != nil { 373 t.Fatalf("Failed to create cert PEM file: %v", err) 374 } 375 pem.Encode(certFile, certPEM) 376 certFile.Close() 377 378 // Save private key to PEM 379 keyBytes, err := x509.MarshalPKCS8PrivateKey(privateKey) 380 if err != nil { 381 t.Fatalf("Failed to marshal private key: %v", err) 382 } 383 keyPEM := &pem.Block{ 384 Type: "PRIVATE KEY", 385 Bytes: keyBytes, 386 } 387 keyFile, err := os.Create(keyPEMFile) 388 if err != nil { 389 t.Fatalf("Failed to create key PEM file: %v", err) 390 } 391 pem.Encode(keyFile, keyPEM) 392 keyFile.Close() 393 394 // Test creating P12 from PEM files 395 p12File := filepath.Join(tempDir, "from_pem.p12") 396 err = CreateP12FromPEM(keyPEMFile, certPEMFile, p12File, "test123") 397 if err != nil { 398 t.Errorf("CreateP12FromPEM failed: %v", err) 399 } 400 401 // Verify by loading the P12 file 402 container, err := QuickLoadP12(p12File, "test123") 403 if err != nil { 404 t.Errorf("Failed to load P12 created from PEM: %v", err) 405 } 406 if container.Certificate.Subject.CommonName != "Test Certificate" { 407 t.Error("P12 from PEM certificate subject mismatch") 408 } 409 410 // Test error cases 411 err = CreateP12FromPEM("", certPEMFile, p12File, "test123") 412 if err == nil { 413 t.Error("Expected error for empty key file") 414 } 415 416 err = CreateP12FromPEM(keyPEMFile, "", p12File, "test123") 417 if err == nil { 418 t.Error("Expected error for empty cert file") 419 } 420 }) 421 422 t.Run("ListCertificatesInP12", func(t *testing.T) { 423 // Create P12 with certificate chain 424 caCerts := []*x509.Certificate{caCertificate} 425 p12File := filepath.Join(tempDir, "list_test.p12") 426 opts := DefaultCreateOptions("test123") 427 err := CreateP12File(p12File, privateKey, certificate, caCerts, opts) 428 if err != nil { 429 t.Fatalf("Failed to create P12 file: %v", err) 430 } 431 432 // Create utility instance 433 utils := P12CertificateUtils{} 434 435 // Test listing certificates 436 certList, err := utils.ListCertificatesInP12(p12File, "test123") 437 if err != nil { 438 t.Errorf("ListCertificatesInP12 failed: %v", err) 439 } 440 if len(certList) == 0 { 441 t.Error("Expected non-empty certificate list") 442 } 443 444 // Should contain info about both leaf and CA certificates 445 foundLeaf := false 446 foundCA := false 447 for _, certInfo := range certList { 448 if subject, ok := certInfo["subject"].(string); ok { 449 if subject == "CN=Test Certificate,O=Test Org,C=US" { 450 foundLeaf = true 451 } 452 if subject == "CN=Test CA,O=Test CA Org,C=US" { 453 foundCA = true 454 } 455 } 456 } 457 if !foundLeaf { 458 t.Error("Leaf certificate not found in list") 459 } 460 if !foundCA { 461 t.Error("CA certificate not found in list") 462 } 463 464 // Test error cases 465 _, err = utils.ListCertificatesInP12("", "test123") 466 if err == nil { 467 t.Error("Expected error for empty filename") 468 } 469 }) 470 471 t.Run("VerifyP12CertificateChain", func(t *testing.T) { 472 // Create P12 with certificate chain 473 caCerts := []*x509.Certificate{caCertificate} 474 p12File := filepath.Join(tempDir, "verify_test.p12") 475 opts := DefaultCreateOptions("test123") 476 err := CreateP12File(p12File, privateKey, certificate, caCerts, opts) 477 if err != nil { 478 t.Fatalf("Failed to create P12 file: %v", err) 479 } 480 481 // Create utility instance 482 utils := P12CertificateUtils{} 483 484 // Test chain verification 485 err = utils.VerifyP12CertificateChain(p12File, "test123") 486 // Note: This might fail since we're using self-signed certificates 487 // but the function should be callable without panicking 488 _ = err 489 490 // Test error cases 491 err = utils.VerifyP12CertificateChain("", "test123") 492 if err == nil { 493 t.Error("Expected error for empty filename") 494 } 495 }) 496 497 t.Run("ConvertP12ChainToPEM", func(t *testing.T) { 498 // Create P12 with certificate chain 499 caCerts := []*x509.Certificate{caCertificate} 500 p12File := filepath.Join(tempDir, "convert_test.p12") 501 opts := DefaultCreateOptions("test123") 502 err := CreateP12File(p12File, privateKey, certificate, caCerts, opts) 503 if err != nil { 504 t.Fatalf("Failed to create P12 file: %v", err) 505 } 506 507 // Create utility instance 508 utils := P12CertificateUtils{} 509 510 // Test converting to PEM 511 outputPrefix := filepath.Join(tempDir, "convert_output") 512 err = utils.ConvertP12ChainToPEM(p12File, "test123", outputPrefix) 513 if err != nil { 514 t.Errorf("ConvertP12ChainToPEM failed: %v", err) 515 } 516 517 // Test error cases 518 err = utils.ConvertP12ChainToPEM("", "test123", outputPrefix) 519 if err == nil { 520 t.Error("Expected error for empty P12 filename") 521 } 522 }) 523 524 t.Run("GetP12CertificateFingerprints", func(t *testing.T) { 525 // Create P12 file 526 p12File := filepath.Join(tempDir, "fingerprint_test.p12") 527 opts := DefaultCreateOptions("test123") 528 err := CreateP12File(p12File, privateKey, certificate, nil, opts) 529 if err != nil { 530 t.Fatalf("Failed to create P12 file: %v", err) 531 } 532 533 // Create utility instance 534 utils := P12CertificateUtils{} 535 536 // Test getting fingerprints 537 fingerprints, err := utils.GetP12CertificateFingerprints(p12File, "test123") 538 if err != nil { 539 t.Errorf("GetP12CertificateFingerprints failed: %v", err) 540 } 541 // The function may return certificate data or actual fingerprints 542 // Let's verify we get at least some data 543 if len(fingerprints) == 0 { 544 t.Error("Expected some fingerprint data") 545 } 546 547 // Print actual data for debugging 548 t.Logf("GetP12CertificateFingerprints returned %d items", len(fingerprints)) 549 550 // Verify all values are non-empty 551 for key, value := range fingerprints { 552 if value == "" { 553 t.Errorf("Value for %s is empty", key) 554 } 555 } 556 557 // Test error cases 558 _, err = utils.GetP12CertificateFingerprints("", "test123") 559 if err == nil { 560 t.Error("Expected error for empty filename") 561 } 562 }) 563 564 // Additional test for ExtractCertificateChain method 565 t.Run("P12Container_ExtractCertificateChain", func(t *testing.T) { 566 // Create P12 with certificate chain 567 caCerts := []*x509.Certificate{caCertificate} 568 opts := DefaultCreateOptions("test123") 569 p12Data, err := CreateP12(privateKey, certificate, caCerts, opts) 570 if err != nil { 571 t.Fatalf("Failed to create P12 data: %v", err) 572 } 573 574 // Parse P12 to get container 575 container, err := ParseP12(p12Data, DefaultLoadOptions("test123")) 576 if err != nil { 577 t.Fatalf("Failed to parse P12 data: %v", err) 578 } 579 580 // Test ExtractCertificateChain method 581 chain := container.ExtractCertificateChain() 582 if len(chain) < 1 { 583 t.Error("Expected at least one certificate in chain") 584 } 585 586 // First certificate should be the leaf certificate 587 if chain[0].Subject.CommonName != "Test Certificate" { 588 t.Error("First certificate in chain should be the leaf certificate") 589 } 590 591 // If we have CA certificates, they should be included 592 if len(chain) > 1 && chain[1].Subject.CommonName != "Test CA" { 593 t.Error("Second certificate should be the CA certificate") 594 } 595 }) 596 } 597 598 func TestHelperFunctions(t *testing.T) { 599 tempDir := t.TempDir() 600 601 // Generate test data 602 privateKey, err := rsa.GenerateKey(rand.Reader, 2048) 603 if err != nil { 604 t.Fatalf("Failed to generate RSA keys: %v", err) 605 } 606 607 // Create expired certificate for testing 608 expiredTemplate := &x509.Certificate{ 609 Subject: pkix.Name{ 610 CommonName: "Expired Certificate", 611 }, 612 NotBefore: time.Now().Add(-2 * 365 * 24 * time.Hour), // 2 years ago 613 NotAfter: time.Now().Add(-365 * 24 * time.Hour), // 1 year ago (expired) 614 KeyUsage: x509.KeyUsageDigitalSignature, 615 SerialNumber: big.NewInt(999), 616 } 617 618 expiredCertDER, err := x509.CreateCertificate(rand.Reader, expiredTemplate, expiredTemplate, &privateKey.PublicKey, privateKey) 619 if err != nil { 620 t.Fatalf("Failed to create expired certificate: %v", err) 621 } 622 623 expiredCertificate, err := x509.ParseCertificate(expiredCertDER) 624 if err != nil { 625 t.Fatalf("Failed to parse expired certificate: %v", err) 626 } 627 628 t.Run("ValidateP12File", func(t *testing.T) { 629 // Create valid P12 file 630 validP12File := filepath.Join(tempDir, "valid_test.p12") 631 err := GenerateTestP12(validP12File, "test123") 632 if err != nil { 633 t.Fatalf("Failed to generate test P12: %v", err) 634 } 635 636 // Test validation 637 err = ValidateP12File(validP12File, "test123") 638 if err != nil { 639 t.Errorf("ValidateP12File failed for valid file: %v", err) 640 } 641 642 // Test with invalid file 643 err = ValidateP12File("nonexistent.p12", "test123") 644 if err == nil { 645 t.Error("Expected error for nonexistent file") 646 } 647 648 // Test with wrong password 649 err = ValidateP12File(validP12File, "wrong_password") 650 if err == nil { 651 t.Error("Expected error for wrong password") 652 } 653 }) 654 655 t.Run("LoadCertificateFromPEMFile", func(t *testing.T) { 656 // Create valid certificate 657 template := &x509.Certificate{ 658 Subject: pkix.Name{ 659 CommonName: "PEM Test Certificate", 660 }, 661 NotBefore: time.Now(), 662 NotAfter: time.Now().Add(365 * 24 * time.Hour), 663 KeyUsage: x509.KeyUsageDigitalSignature, 664 SerialNumber: big.NewInt(123), 665 } 666 667 certDER, err := x509.CreateCertificate(rand.Reader, template, template, &privateKey.PublicKey, privateKey) 668 if err != nil { 669 t.Fatalf("Failed to create certificate: %v", err) 670 } 671 672 certificate, err := x509.ParseCertificate(certDER) 673 if err != nil { 674 t.Fatalf("Failed to parse certificate: %v", err) 675 } 676 677 // Save certificate to PEM file 678 certPEMFile := filepath.Join(tempDir, "test_cert.pem") 679 certPEM := &pem.Block{ 680 Type: "CERTIFICATE", 681 Bytes: certificate.Raw, 682 } 683 certFile, err := os.Create(certPEMFile) 684 if err != nil { 685 t.Fatalf("Failed to create cert PEM file: %v", err) 686 } 687 pem.Encode(certFile, certPEM) 688 certFile.Close() 689 690 // Test loading certificate from PEM file 691 loadedCert, err := LoadCertificateFromPEMFile(certPEMFile) 692 if err != nil { 693 t.Errorf("LoadCertificateFromPEMFile failed: %v", err) 694 } 695 if loadedCert.Certificate.Subject.CommonName != "PEM Test Certificate" { 696 t.Error("Loaded certificate subject mismatch") 697 } 698 699 // Test error cases 700 _, err = LoadCertificateFromPEMFile("") 701 if err == nil { 702 t.Error("Expected error for empty filename") 703 } 704 705 _, err = LoadCertificateFromPEMFile("nonexistent.pem") 706 if err == nil { 707 t.Error("Expected error for nonexistent file") 708 } 709 }) 710 711 t.Run("LoadPrivateKeyFromPEM", func(t *testing.T) { 712 // Create PEM private key file 713 keyPEMFile := filepath.Join(tempDir, "test_key.pem") 714 keyBytes, err := x509.MarshalPKCS8PrivateKey(privateKey) 715 if err != nil { 716 t.Fatalf("Failed to marshal private key: %v", err) 717 } 718 719 keyPEM := &pem.Block{ 720 Type: "PRIVATE KEY", 721 Bytes: keyBytes, 722 } 723 keyFile, err := os.Create(keyPEMFile) 724 if err != nil { 725 t.Fatalf("Failed to create key PEM file: %v", err) 726 } 727 pem.Encode(keyFile, keyPEM) 728 keyFile.Close() 729 730 // Test loading private key from PEM file 731 loadedKey, err := LoadPrivateKeyFromPEM(keyPEMFile) 732 if err != nil { 733 t.Errorf("LoadPrivateKeyFromPEM failed: %v", err) 734 } 735 if loadedKey == nil { 736 t.Error("Expected non-nil private key") 737 } 738 739 // Test with RSA key specifically 740 if rsaKey, ok := loadedKey.(*rsa.PrivateKey); ok { 741 if rsaKey.Size() != privateKey.Size() { 742 t.Error("RSA key size mismatch") 743 } 744 } else { 745 t.Error("Expected RSA private key") 746 } 747 748 // Test error cases 749 _, err = LoadPrivateKeyFromPEM("") 750 if err == nil { 751 t.Error("Expected error for empty filename") 752 } 753 754 _, err = LoadPrivateKeyFromPEM("nonexistent.pem") 755 if err == nil { 756 t.Error("Expected error for nonexistent file") 757 } 758 }) 759 760 // Test helper validation functions with different key types 761 t.Run("HelperValidationFunctions", func(t *testing.T) { 762 // Generate ECDSA key pair for testing 763 ecdsaPrivKey, err := algo.GenerateECDSAKeyPair(algo.P256) 764 if err != nil { 765 t.Fatalf("Failed to generate ECDSA key pair: %v", err) 766 } 767 768 // Generate Ed25519 key pair for testing 769 ed25519PrivKey, err := algo.GenerateEd25519KeyPair() 770 if err != nil { 771 t.Fatalf("Failed to generate Ed25519 key pair: %v", err) 772 } 773 774 // Test validateCertificateExpiration with expired certificate 775 err = validateCertificateExpiration(expiredCertificate) 776 if err == nil { 777 t.Error("Expected error for expired certificate") 778 } 779 780 // Test validateKeyPairMatch with mismatched keys 781 err = validateKeyPairMatch(expiredCertificate, ecdsaPrivKey.PrivateKey) 782 if err == nil { 783 t.Error("Expected error for mismatched key pair") 784 } 785 786 // Test getPrivateKeyType with different key types 787 if keyType := getPrivateKeyType(privateKey); keyType != "RSA" { 788 t.Errorf("Expected RSA key type, got %s", keyType) 789 } 790 791 if keyType := getPrivateKeyType(ecdsaPrivKey.PrivateKey); keyType != "ECDSA" { 792 t.Errorf("Expected ECDSA key type, got %s", keyType) 793 } 794 795 if keyType := getPrivateKeyType(ed25519PrivKey.PrivateKey); keyType != "Ed25519" { 796 t.Errorf("Expected Ed25519 key type, got %s", keyType) 797 } 798 799 if keyType := getPrivateKeyType("invalid"); keyType != "Unknown (string)" { 800 t.Errorf("Expected 'Unknown (string)' key type for invalid input, got %s", keyType) 801 } 802 }) 803 }