github.com/jasoet/gopki@v1.15.0/pkcs12/keypair_integration_test.go (about) 1 package pkcs12 2 3 import ( 4 "crypto/ecdsa" 5 "crypto/ed25519" 6 "crypto/rand" 7 "crypto/rsa" 8 "crypto/x509" 9 "crypto/x509/pkix" 10 "math/big" 11 "os" 12 "path/filepath" 13 "testing" 14 "time" 15 16 "github.com/jasoet/gopki/keypair" 17 "github.com/jasoet/gopki/keypair/algo" 18 ) 19 20 func TestToP12KeyPairFunctions(t *testing.T) { 21 tempDir := t.TempDir() 22 password := "test123" 23 24 // Helper function to create certificate 25 createCertificate := func(keyPair keypair.GenericKeyPair) *x509.Certificate { 26 template := &x509.Certificate{ 27 Subject: pkix.Name{ 28 CommonName: "Test Certificate", 29 Organization: []string{"Test Org"}, 30 Country: []string{"US"}, 31 }, 32 NotBefore: time.Now(), 33 NotAfter: time.Now().Add(24 * time.Hour), 34 KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment, 35 SerialNumber: big.NewInt(1), 36 } 37 38 var publicKey any 39 var privateKey any 40 41 switch kp := keyPair.(type) { 42 case *algo.RSAKeyPair: 43 publicKey = kp.PublicKey 44 privateKey = kp.PrivateKey 45 case *algo.ECDSAKeyPair: 46 publicKey = kp.PublicKey 47 privateKey = kp.PrivateKey 48 case *algo.Ed25519KeyPair: 49 publicKey = kp.PublicKey 50 privateKey = kp.PrivateKey 51 default: 52 t.Fatalf("Unsupported key pair type: %T", keyPair) 53 return nil 54 } 55 56 certDER, err := x509.CreateCertificate(rand.Reader, template, template, publicKey, privateKey) 57 if err != nil { 58 t.Fatalf("Failed to create certificate: %v", err) 59 } 60 61 certificate, err := x509.ParseCertificate(certDER) 62 if err != nil { 63 t.Fatalf("Failed to parse certificate: %v", err) 64 } 65 66 return certificate 67 } 68 69 t.Run("ToP12KeyPair RSA", func(t *testing.T) { 70 // Generate RSA key pair 71 manager, err := keypair.Generate[algo.KeySize, *algo.RSAKeyPair, *rsa.PrivateKey, *rsa.PublicKey](algo.KeySize2048) 72 if err != nil { 73 t.Fatalf("Failed to generate RSA keys: %v", err) 74 } 75 rsaKeys := manager.KeyPair() 76 77 // Create certificate 78 certificate := createCertificate(rsaKeys) 79 80 // Test ToP12KeyPair generic function 81 p12Data, err := ToP12KeyPair(rsaKeys, certificate, password) 82 if err != nil { 83 t.Fatalf("ToP12KeyPair failed: %v", err) 84 } 85 86 if len(p12Data) == 0 { 87 t.Error("P12 data is empty") 88 } 89 90 // Test ToP12RSAKeyPair specific function 91 p12DataRSA, err := ToP12RSAKeyPair(rsaKeys, certificate, password) 92 if err != nil { 93 t.Fatalf("ToP12RSAKeyPair failed: %v", err) 94 } 95 96 if len(p12DataRSA) == 0 { 97 t.Error("P12 RSA data is empty") 98 } 99 }) 100 101 t.Run("ToP12KeyPair ECDSA", func(t *testing.T) { 102 // Generate ECDSA key pair 103 manager, err := keypair.Generate[algo.ECDSACurve, *algo.ECDSAKeyPair, *ecdsa.PrivateKey, *ecdsa.PublicKey](algo.P256) 104 if err != nil { 105 t.Fatalf("Failed to generate ECDSA keys: %v", err) 106 } 107 ecdsaKeys := manager.KeyPair() 108 109 // Create certificate 110 certificate := createCertificate(ecdsaKeys) 111 112 // Test ToP12KeyPair generic function 113 p12Data, err := ToP12KeyPair(ecdsaKeys, certificate, password) 114 if err != nil { 115 t.Fatalf("ToP12KeyPair failed: %v", err) 116 } 117 118 if len(p12Data) == 0 { 119 t.Error("P12 data is empty") 120 } 121 122 // Test ToP12ECDSAKeyPair specific function 123 p12DataECDSA, err := ToP12ECDSAKeyPair(ecdsaKeys, certificate, password) 124 if err != nil { 125 t.Fatalf("ToP12ECDSAKeyPair failed: %v", err) 126 } 127 128 if len(p12DataECDSA) == 0 { 129 t.Error("P12 ECDSA data is empty") 130 } 131 }) 132 133 t.Run("ToP12KeyPair Ed25519", func(t *testing.T) { 134 // Generate Ed25519 key pair 135 manager, err := keypair.Generate[algo.Ed25519Config, *algo.Ed25519KeyPair, ed25519.PrivateKey, ed25519.PublicKey]("") 136 if err != nil { 137 t.Fatalf("Failed to generate Ed25519 keys: %v", err) 138 } 139 ed25519Keys := manager.KeyPair() 140 141 // Create certificate 142 certificate := createCertificate(ed25519Keys) 143 144 // Test ToP12KeyPair generic function 145 p12Data, err := ToP12KeyPair(ed25519Keys, certificate, password) 146 if err != nil { 147 t.Fatalf("ToP12KeyPair failed: %v", err) 148 } 149 150 if len(p12Data) == 0 { 151 t.Error("P12 data is empty") 152 } 153 154 // Test ToP12Ed25519KeyPair specific function 155 p12DataEd25519, err := ToP12Ed25519KeyPair(ed25519Keys, certificate, password) 156 if err != nil { 157 t.Fatalf("ToP12Ed25519KeyPair failed: %v", err) 158 } 159 160 if len(p12DataEd25519) == 0 { 161 t.Error("P12 Ed25519 data is empty") 162 } 163 }) 164 165 t.Run("ToP12KeyPairFile", func(t *testing.T) { 166 // Generate RSA key pair 167 manager, err := keypair.Generate[algo.KeySize, *algo.RSAKeyPair, *rsa.PrivateKey, *rsa.PublicKey](algo.KeySize2048) 168 if err != nil { 169 t.Fatalf("Failed to generate RSA keys: %v", err) 170 } 171 rsaKeys := manager.KeyPair() 172 173 // Create certificate 174 certificate := createCertificate(rsaKeys) 175 176 // Test ToP12KeyPairFile 177 p12File := filepath.Join(tempDir, "test_rsa.p12") 178 err = ToP12KeyPairFile(rsaKeys, certificate, p12File, password) 179 if err != nil { 180 t.Fatalf("ToP12KeyPairFile failed: %v", err) 181 } 182 183 // Verify file exists 184 if _, err := os.Stat(p12File); os.IsNotExist(err) { 185 t.Error("P12 file was not created") 186 } 187 188 // Verify file size 189 fileInfo, err := os.Stat(p12File) 190 if err != nil { 191 t.Fatalf("Failed to stat P12 file: %v", err) 192 } 193 if fileInfo.Size() == 0 { 194 t.Error("P12 file is empty") 195 } 196 }) 197 } 198 199 func TestFromP12KeyPairFunctions(t *testing.T) { 200 tempDir := t.TempDir() 201 password := "test123" 202 203 // Helper function to create certificate using x509 directly 204 createSelfSignedCertificate := func(keyPair keypair.GenericKeyPair) *x509.Certificate { 205 template := &x509.Certificate{ 206 Subject: pkix.Name{ 207 CommonName: "Test Certificate", 208 Organization: []string{"Test Org"}, 209 Country: []string{"US"}, 210 }, 211 NotBefore: time.Now(), 212 NotAfter: time.Now().Add(24 * time.Hour), 213 KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment, 214 SerialNumber: big.NewInt(1), 215 } 216 217 var publicKey any 218 var privateKey any 219 220 switch kp := keyPair.(type) { 221 case *algo.RSAKeyPair: 222 publicKey = kp.PublicKey 223 privateKey = kp.PrivateKey 224 case *algo.ECDSAKeyPair: 225 publicKey = kp.PublicKey 226 privateKey = kp.PrivateKey 227 case *algo.Ed25519KeyPair: 228 publicKey = kp.PublicKey 229 privateKey = kp.PrivateKey 230 } 231 232 certDER, err := x509.CreateCertificate(rand.Reader, template, template, publicKey, privateKey) 233 if err != nil { 234 t.Fatalf("Failed to create certificate: %v", err) 235 } 236 237 certificate, err := x509.ParseCertificate(certDER) 238 if err != nil { 239 t.Fatalf("Failed to parse certificate: %v", err) 240 } 241 242 return certificate 243 } 244 245 t.Run("FromP12KeyPair RSA Round Trip", func(t *testing.T) { 246 // Generate RSA key pair 247 manager, err := keypair.Generate[algo.KeySize, *algo.RSAKeyPair, *rsa.PrivateKey, *rsa.PublicKey](algo.KeySize2048) 248 if err != nil { 249 t.Fatalf("Failed to generate RSA keys: %v", err) 250 } 251 originalKeys := manager.KeyPair() 252 253 // Create certificate 254 originalCert := createSelfSignedCertificate(originalKeys) 255 256 // Export to P12 257 p12Data, err := ToP12KeyPair(originalKeys, originalCert, password) 258 if err != nil { 259 t.Fatalf("ToP12KeyPair failed: %v", err) 260 } 261 262 // Import using generic function 263 loadedKeys, loadedCert, caCerts, err := FromP12KeyPair[*algo.RSAKeyPair](p12Data, password) 264 if err != nil { 265 t.Fatalf("FromP12KeyPair failed: %v", err) 266 } 267 268 // Verify loaded keys 269 if loadedKeys == nil { 270 t.Fatal("Loaded keys are nil") 271 } 272 if loadedKeys.PrivateKey == nil { 273 t.Error("Loaded private key is nil") 274 } 275 if loadedKeys.PublicKey == nil { 276 t.Error("Loaded public key is nil") 277 } 278 279 // Verify certificate 280 if loadedCert == nil { 281 t.Fatal("Loaded certificate is nil") 282 } 283 if loadedCert.Subject.CommonName != "Test Certificate" { 284 t.Error("Certificate subject mismatch") 285 } 286 287 // Verify CA certificates 288 if len(caCerts) != 0 { 289 t.Errorf("Expected 0 CA certificates, got %d", len(caCerts)) 290 } 291 292 // Test type-specific function 293 loadedKeysRSA, loadedCertRSA, caCertsRSA, err := FromP12RSAKeyPair(p12Data, password) 294 if err != nil { 295 t.Fatalf("FromP12RSAKeyPair failed: %v", err) 296 } 297 298 if loadedKeysRSA == nil { 299 t.Fatal("Loaded RSA keys are nil") 300 } 301 if loadedCertRSA == nil { 302 t.Fatal("Loaded RSA certificate is nil") 303 } 304 if len(caCertsRSA) != 0 { 305 t.Errorf("Expected 0 RSA CA certificates, got %d", len(caCertsRSA)) 306 } 307 }) 308 309 t.Run("FromP12KeyPair ECDSA Round Trip", func(t *testing.T) { 310 // Generate ECDSA key pair 311 manager, err := keypair.Generate[algo.ECDSACurve, *algo.ECDSAKeyPair, *ecdsa.PrivateKey, *ecdsa.PublicKey](algo.P256) 312 if err != nil { 313 t.Fatalf("Failed to generate ECDSA keys: %v", err) 314 } 315 originalKeys := manager.KeyPair() 316 317 // Create certificate 318 originalCert := createSelfSignedCertificate(originalKeys) 319 320 // Export to P12 321 p12Data, err := ToP12KeyPair(originalKeys, originalCert, password) 322 if err != nil { 323 t.Fatalf("ToP12KeyPair failed: %v", err) 324 } 325 326 // Import using generic function 327 loadedKeys, loadedCert, _, err := FromP12KeyPair[*algo.ECDSAKeyPair](p12Data, password) 328 if err != nil { 329 t.Fatalf("FromP12KeyPair failed: %v", err) 330 } 331 332 // Verify loaded keys 333 if loadedKeys == nil { 334 t.Fatal("Loaded keys are nil") 335 } 336 if loadedKeys.PrivateKey == nil { 337 t.Error("Loaded private key is nil") 338 } 339 if loadedKeys.PublicKey == nil { 340 t.Error("Loaded public key is nil") 341 } 342 343 // Verify certificate 344 if loadedCert == nil { 345 t.Fatal("Loaded certificate is nil") 346 } 347 if loadedCert.Subject.CommonName != "Test Certificate" { 348 t.Error("Certificate subject mismatch") 349 } 350 351 // Test type-specific function 352 loadedKeysECDSA, _, _, err := FromP12ECDSAKeyPair(p12Data, password) 353 if err != nil { 354 t.Fatalf("FromP12ECDSAKeyPair failed: %v", err) 355 } 356 357 if loadedKeysECDSA == nil { 358 t.Fatal("Loaded ECDSA keys are nil") 359 } 360 }) 361 362 t.Run("FromP12KeyPair Ed25519 Round Trip", func(t *testing.T) { 363 // Generate Ed25519 key pair 364 manager, err := keypair.Generate[algo.Ed25519Config, *algo.Ed25519KeyPair, ed25519.PrivateKey, ed25519.PublicKey]("") 365 if err != nil { 366 t.Fatalf("Failed to generate Ed25519 keys: %v", err) 367 } 368 originalKeys := manager.KeyPair() 369 370 // Create certificate 371 originalCert := createSelfSignedCertificate(originalKeys) 372 373 // Export to P12 374 p12Data, err := ToP12KeyPair(originalKeys, originalCert, password) 375 if err != nil { 376 t.Fatalf("ToP12KeyPair failed: %v", err) 377 } 378 379 // Import using generic function 380 loadedKeys, loadedCert, _, err := FromP12KeyPair[*algo.Ed25519KeyPair](p12Data, password) 381 if err != nil { 382 t.Fatalf("FromP12KeyPair failed: %v", err) 383 } 384 385 // Verify loaded keys 386 if loadedKeys == nil { 387 t.Fatal("Loaded keys are nil") 388 } 389 if len(loadedKeys.PrivateKey) == 0 { 390 t.Error("Loaded private key is empty") 391 } 392 if len(loadedKeys.PublicKey) == 0 { 393 t.Error("Loaded public key is empty") 394 } 395 396 // Verify certificate 397 if loadedCert == nil { 398 t.Fatal("Loaded certificate is nil") 399 } 400 401 // Test type-specific function 402 loadedKeysEd25519, _, _, err := FromP12Ed25519KeyPair(p12Data, password) 403 if err != nil { 404 t.Fatalf("FromP12Ed25519KeyPair failed: %v", err) 405 } 406 407 if loadedKeysEd25519 == nil { 408 t.Fatal("Loaded Ed25519 keys are nil") 409 } 410 }) 411 412 t.Run("FromP12KeyPairFile", func(t *testing.T) { 413 // Generate RSA key pair and create P12 file 414 manager, err := keypair.Generate[algo.KeySize, *algo.RSAKeyPair, *rsa.PrivateKey, *rsa.PublicKey](algo.KeySize2048) 415 if err != nil { 416 t.Fatalf("Failed to generate RSA keys: %v", err) 417 } 418 rsaKeys := manager.KeyPair() 419 420 certificate := createSelfSignedCertificate(rsaKeys) 421 422 p12File := filepath.Join(tempDir, "test_file.p12") 423 err = ToP12KeyPairFile(rsaKeys, certificate, p12File, password) 424 if err != nil { 425 t.Fatalf("ToP12KeyPairFile failed: %v", err) 426 } 427 428 // Load using FromP12KeyPairFile generic function 429 loadedKeys, loadedCert, caCerts, err := FromP12KeyPairFile[*algo.RSAKeyPair](p12File, password) 430 if err != nil { 431 t.Fatalf("FromP12KeyPairFile failed: %v", err) 432 } 433 434 // Verify loaded data 435 if loadedKeys == nil { 436 t.Fatal("Loaded keys are nil") 437 } 438 if loadedCert == nil { 439 t.Fatal("Loaded certificate is nil") 440 } 441 if len(caCerts) != 0 { 442 t.Errorf("Expected 0 CA certificates, got %d", len(caCerts)) 443 } 444 }) 445 } 446 447 func TestImportFromP12KeyPairWithValidation(t *testing.T) { 448 tempDir := t.TempDir() 449 password := "test123" 450 451 // Helper function to create certificate 452 createValidationCertificate := func(keyPair keypair.GenericKeyPair) *x509.Certificate { 453 template := &x509.Certificate{ 454 Subject: pkix.Name{ 455 CommonName: "Validation Test", 456 Organization: []string{"Test Org"}, 457 }, 458 NotBefore: time.Now(), 459 NotAfter: time.Now().Add(24 * time.Hour), 460 KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment, 461 SerialNumber: big.NewInt(1), 462 } 463 464 var publicKey any 465 var privateKey any 466 467 switch kp := keyPair.(type) { 468 case *algo.RSAKeyPair: 469 publicKey = kp.PublicKey 470 privateKey = kp.PrivateKey 471 case *algo.ECDSAKeyPair: 472 publicKey = kp.PublicKey 473 privateKey = kp.PrivateKey 474 case *algo.Ed25519KeyPair: 475 publicKey = kp.PublicKey 476 privateKey = kp.PrivateKey 477 } 478 479 certDER, err := x509.CreateCertificate(rand.Reader, template, template, publicKey, privateKey) 480 if err != nil { 481 t.Fatalf("Failed to create certificate: %v", err) 482 } 483 484 certificate, err := x509.ParseCertificate(certDER) 485 if err != nil { 486 t.Fatalf("Failed to parse certificate: %v", err) 487 } 488 489 return certificate 490 } 491 492 t.Run("Valid P12 Import", func(t *testing.T) { 493 // Generate RSA key pair 494 manager, err := keypair.Generate[algo.KeySize, *algo.RSAKeyPair, *rsa.PrivateKey, *rsa.PublicKey](algo.KeySize2048) 495 if err != nil { 496 t.Fatalf("Failed to generate RSA keys: %v", err) 497 } 498 rsaKeys := manager.KeyPair() 499 500 // Create certificate 501 certificate := createValidationCertificate(rsaKeys) 502 503 // Create P12 file 504 p12File := filepath.Join(tempDir, "validation_test.p12") 505 err = ToP12KeyPairFile(rsaKeys, certificate, p12File, password) 506 if err != nil { 507 t.Fatalf("ToP12KeyPairFile failed: %v", err) 508 } 509 510 // Import with validation 511 loadedKeys, loadedCert, caCerts, err := ImportFromP12KeyPairWithValidation[*algo.RSAKeyPair](p12File, password) 512 if err != nil { 513 t.Fatalf("ImportFromP12KeyPairWithValidation failed: %v", err) 514 } 515 516 // Verify loaded data 517 if loadedKeys == nil { 518 t.Fatal("Loaded keys are nil") 519 } 520 if loadedCert == nil { 521 t.Fatal("Loaded certificate is nil") 522 } 523 if loadedCert.Subject.CommonName != "Validation Test" { 524 t.Error("Certificate subject mismatch") 525 } 526 if len(caCerts) != 0 { 527 t.Errorf("Expected 0 CA certificates, got %d", len(caCerts)) 528 } 529 }) 530 } 531 532 func TestP12KeyPairErrorCases(t *testing.T) { 533 password := "test123" 534 535 t.Run("ToP12KeyPair Error Cases", func(t *testing.T) { 536 manager, _ := keypair.Generate[algo.KeySize, *algo.RSAKeyPair, *rsa.PrivateKey, *rsa.PublicKey](algo.KeySize2048) 537 rsaKeys := manager.KeyPair() 538 539 // Create a test certificate directly 540 template := &x509.Certificate{ 541 Subject: pkix.Name{CommonName: "Test"}, 542 NotBefore: time.Now(), 543 NotAfter: time.Now().Add(24 * time.Hour), 544 KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment, 545 SerialNumber: big.NewInt(1), 546 } 547 certDER, _ := x509.CreateCertificate(rand.Reader, template, template, rsaKeys.PublicKey, rsaKeys.PrivateKey) 548 certificate, _ := x509.ParseCertificate(certDER) 549 550 // Nil key pair 551 _, err := ToP12KeyPair[*algo.RSAKeyPair](nil, certificate, password) 552 if err == nil { 553 t.Error("Expected error for nil key pair") 554 } 555 556 // Nil certificate 557 _, err = ToP12KeyPair(rsaKeys, nil, password) 558 if err == nil { 559 t.Error("Expected error for nil certificate") 560 } 561 562 // Empty password 563 _, err = ToP12KeyPair(rsaKeys, certificate, "") 564 if err == nil { 565 t.Error("Expected error for empty password") 566 } 567 }) 568 569 t.Run("FromP12KeyPair Error Cases", func(t *testing.T) { 570 // Empty data 571 _, _, _, err := FromP12KeyPair[*algo.RSAKeyPair]([]byte{}, password) 572 if err == nil { 573 t.Error("Expected error for empty P12 data") 574 } 575 576 // Empty password 577 _, _, _, err = FromP12KeyPair[*algo.RSAKeyPair]([]byte("dummy"), "") 578 if err == nil { 579 t.Error("Expected error for empty password") 580 } 581 582 // Invalid P12 data 583 _, _, _, err = FromP12KeyPair[*algo.RSAKeyPair]([]byte("invalid p12 data"), password) 584 if err == nil { 585 t.Error("Expected error for invalid P12 data") 586 } 587 }) 588 589 t.Run("Type Mismatch Error", func(t *testing.T) { 590 // Create RSA P12 data 591 manager, _ := keypair.Generate[algo.KeySize, *algo.RSAKeyPair, *rsa.PrivateKey, *rsa.PublicKey](algo.KeySize2048) 592 rsaKeys := manager.KeyPair() 593 594 // Create certificate directly 595 template := &x509.Certificate{ 596 Subject: pkix.Name{CommonName: "Type Test"}, 597 NotBefore: time.Now(), 598 NotAfter: time.Now().Add(24 * time.Hour), 599 KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment, 600 SerialNumber: big.NewInt(1), 601 } 602 certDER, _ := x509.CreateCertificate(rand.Reader, template, template, rsaKeys.PublicKey, rsaKeys.PrivateKey) 603 certificate, _ := x509.ParseCertificate(certDER) 604 p12Data, _ := ToP12KeyPair(rsaKeys, certificate, password) 605 606 // Try to load as ECDSA (should fail) 607 _, _, _, err := FromP12KeyPair[*algo.ECDSAKeyPair](p12Data, password) 608 if err == nil { 609 t.Error("Expected error for type mismatch (RSA P12 loaded as ECDSA)") 610 } 611 612 // Try to load as Ed25519 (should fail) 613 _, _, _, err = FromP12KeyPair[*algo.Ed25519KeyPair](p12Data, password) 614 if err == nil { 615 t.Error("Expected error for type mismatch (RSA P12 loaded as Ed25519)") 616 } 617 }) 618 619 t.Run("FromP12KeyPairFile Error Cases", func(t *testing.T) { 620 // Non-existent file 621 _, _, _, err := FromP12KeyPairFile[*algo.RSAKeyPair]("nonexistent.p12", password) 622 if err == nil { 623 t.Error("Expected error for non-existent file") 624 } 625 626 // Empty filename 627 _, _, _, err = FromP12KeyPairFile[*algo.RSAKeyPair]("", password) 628 if err == nil { 629 t.Error("Expected error for empty filename") 630 } 631 632 // Empty password 633 _, _, _, err = FromP12KeyPairFile[*algo.RSAKeyPair]("dummy.p12", "") 634 if err == nil { 635 t.Error("Expected error for empty password") 636 } 637 }) 638 } 639 640 func TestExportKeyPairWithChain(t *testing.T) { 641 tempDir := t.TempDir() 642 password := "test123" 643 644 t.Run("Export with Certificate Chain", func(t *testing.T) { 645 // Generate RSA key pair 646 manager, err := keypair.Generate[algo.KeySize, *algo.RSAKeyPair, *rsa.PrivateKey, *rsa.PublicKey](algo.KeySize2048) 647 if err != nil { 648 t.Fatalf("Failed to generate RSA keys: %v", err) 649 } 650 rsaKeys := manager.KeyPair() 651 652 // Create main certificate 653 template := &x509.Certificate{ 654 Subject: pkix.Name{ 655 CommonName: "End Entity Cert", 656 Organization: []string{"Test Org"}, 657 }, 658 NotBefore: time.Now(), 659 NotAfter: time.Now().Add(24 * time.Hour), 660 KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment, 661 SerialNumber: big.NewInt(1), 662 } 663 certDER, err := x509.CreateCertificate(rand.Reader, template, template, rsaKeys.PublicKey, rsaKeys.PrivateKey) 664 if err != nil { 665 t.Fatalf("Failed to create certificate: %v", err) 666 } 667 certificate, err := x509.ParseCertificate(certDER) 668 if err != nil { 669 t.Fatalf("Failed to parse certificate: %v", err) 670 } 671 672 // Create a dummy CA certificate for the chain 673 caManager, _ := keypair.Generate[algo.KeySize, *algo.RSAKeyPair, *rsa.PrivateKey, *rsa.PublicKey](algo.KeySize2048) 674 caKeys := caManager.KeyPair() 675 caTemplate := &x509.Certificate{ 676 Subject: pkix.Name{ 677 CommonName: "Test CA", 678 Organization: []string{"CA Org"}, 679 }, 680 NotBefore: time.Now(), 681 NotAfter: time.Now().Add(24 * time.Hour), 682 KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment, 683 SerialNumber: big.NewInt(2), 684 IsCA: true, 685 } 686 caCertDER, err := x509.CreateCertificate(rand.Reader, caTemplate, caTemplate, caKeys.PublicKey, caKeys.PrivateKey) 687 if err != nil { 688 t.Fatalf("Failed to create CA certificate: %v", err) 689 } 690 caCertificate, err := x509.ParseCertificate(caCertDER) 691 if err != nil { 692 t.Fatalf("Failed to parse CA certificate: %v", err) 693 } 694 695 // Export with chain 696 p12File := filepath.Join(tempDir, "chain_test.p12") 697 caCerts := []*x509.Certificate{caCertificate} 698 err = ExportKeyPairWithChain(rsaKeys, certificate, caCerts, p12File, password) 699 if err != nil { 700 t.Fatalf("ExportKeyPairWithChain failed: %v", err) 701 } 702 703 // Verify file was created 704 if _, err := os.Stat(p12File); os.IsNotExist(err) { 705 t.Error("P12 file with chain was not created") 706 } 707 708 // Load and verify the chain was included 709 loadedKeys, loadedCert, loadedCaCerts, err := FromP12KeyPairFile[*algo.RSAKeyPair](p12File, password) 710 if err != nil { 711 t.Fatalf("Failed to load P12 with chain: %v", err) 712 } 713 714 if loadedKeys == nil { 715 t.Fatal("Loaded keys are nil") 716 } 717 if loadedCert == nil { 718 t.Fatal("Loaded certificate is nil") 719 } 720 if len(loadedCaCerts) == 0 { 721 t.Error("Expected CA certificates in chain, got none") 722 } 723 }) 724 } 725 726 func TestConvertP12ToPEM(t *testing.T) { 727 tempDir := t.TempDir() 728 password := "test123" 729 730 t.Run("Convert RSA P12 to PEM", func(t *testing.T) { 731 // Generate RSA key pair and create P12 732 manager, err := keypair.Generate[algo.KeySize, *algo.RSAKeyPair, *rsa.PrivateKey, *rsa.PublicKey](algo.KeySize2048) 733 if err != nil { 734 t.Fatalf("Failed to generate RSA keys: %v", err) 735 } 736 rsaKeys := manager.KeyPair() 737 738 // Create certificate directly 739 template := &x509.Certificate{ 740 Subject: pkix.Name{CommonName: "Convert Test"}, 741 NotBefore: time.Now(), 742 NotAfter: time.Now().Add(24 * time.Hour), 743 KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment, 744 SerialNumber: big.NewInt(1), 745 } 746 certDER, err := x509.CreateCertificate(rand.Reader, template, template, rsaKeys.PublicKey, rsaKeys.PrivateKey) 747 if err != nil { 748 t.Fatalf("Failed to create certificate: %v", err) 749 } 750 certificate, err := x509.ParseCertificate(certDER) 751 if err != nil { 752 t.Fatalf("Failed to parse certificate: %v", err) 753 } 754 755 p12File := filepath.Join(tempDir, "convert_test.p12") 756 err = ToP12KeyPairFile(rsaKeys, certificate, p12File, password) 757 if err != nil { 758 t.Fatalf("ToP12KeyPairFile failed: %v", err) 759 } 760 761 // Convert to PEM 762 privateKeyFile := filepath.Join(tempDir, "converted_private.pem") 763 certFile := filepath.Join(tempDir, "converted_cert.pem") 764 765 err = ConvertP12KeyPairToPEM(p12File, password, privateKeyFile, certFile) 766 if err != nil { 767 t.Fatalf("ConvertP12KeyPairToPEM failed: %v", err) 768 } 769 770 // Verify PEM files were created 771 if _, err := os.Stat(privateKeyFile); os.IsNotExist(err) { 772 t.Error("Private key PEM file was not created") 773 } 774 if _, err := os.Stat(privateKeyFile + ".pub"); os.IsNotExist(err) { 775 t.Error("Public key PEM file was not created") 776 } 777 }) 778 } 779 780 // TestToP12KeyPairFileErrorHandling tests error handling in ToP12KeyPairFile function 781 func TestToP12KeyPairFileErrorHandling(t *testing.T) { 782 tempDir := t.TempDir() 783 password := "test123" 784 785 // Generate RSA key pair for testing 786 manager, err := keypair.Generate[algo.KeySize, *algo.RSAKeyPair, *rsa.PrivateKey, *rsa.PublicKey](algo.KeySize2048) 787 if err != nil { 788 t.Fatalf("Failed to generate RSA keys: %v", err) 789 } 790 rsaKeys := manager.KeyPair() 791 792 // Create a test certificate 793 certificate := createTestCertificate(t, rsaKeys) 794 795 t.Run("NilKeyPairError", func(t *testing.T) { 796 filename := filepath.Join(tempDir, "nil_keypair.p12") 797 err := ToP12KeyPairFile[*algo.RSAKeyPair](nil, certificate, filename, password) 798 if err == nil { 799 t.Error("Expected error when key pair is nil") 800 } 801 if err != nil && !contains(err.Error(), "key pair is required") { 802 t.Errorf("Expected 'key pair is required' error, got: %v", err) 803 } 804 }) 805 806 t.Run("NilCertificateError", func(t *testing.T) { 807 filename := filepath.Join(tempDir, "nil_cert.p12") 808 err := ToP12KeyPairFile(rsaKeys, nil, filename, password) 809 if err == nil { 810 t.Error("Expected error when certificate is nil") 811 } 812 if err != nil && !contains(err.Error(), "certificate is required") { 813 t.Errorf("Expected 'certificate is required' error, got: %v", err) 814 } 815 }) 816 817 t.Run("EmptyPasswordError", func(t *testing.T) { 818 filename := filepath.Join(tempDir, "empty_password.p12") 819 err := ToP12KeyPairFile(rsaKeys, certificate, filename, "") 820 if err == nil { 821 t.Error("Expected error when password is empty") 822 } 823 if err != nil && !contains(err.Error(), "password is required") { 824 t.Errorf("Expected password error, got: %v", err) 825 } 826 }) 827 828 t.Run("MultipleAlgorithmTypes", func(t *testing.T) { 829 // Test ECDSA 830 ecdsaManager, err := keypair.Generate[algo.ECDSACurve, *algo.ECDSAKeyPair, *ecdsa.PrivateKey, *ecdsa.PublicKey](algo.P256) 831 if err != nil { 832 t.Fatalf("Failed to generate ECDSA keys: %v", err) 833 } 834 ecdsaKeys := ecdsaManager.KeyPair() 835 ecdsaCert := createTestCertificate(t, ecdsaKeys) 836 837 ecdsaFilename := filepath.Join(tempDir, "ecdsa_test.p12") 838 err = ToP12KeyPairFile(ecdsaKeys, ecdsaCert, ecdsaFilename, password) 839 if err != nil { 840 t.Errorf("Failed to create ECDSA P12 file: %v", err) 841 } 842 843 // Verify file was created 844 if _, err := os.Stat(ecdsaFilename); os.IsNotExist(err) { 845 t.Error("ECDSA P12 file was not created") 846 } 847 848 // Test Ed25519 849 ed25519Manager, err := keypair.Generate[algo.Ed25519Config, *algo.Ed25519KeyPair, ed25519.PrivateKey, ed25519.PublicKey]("") 850 if err != nil { 851 t.Fatalf("Failed to generate Ed25519 keys: %v", err) 852 } 853 ed25519Keys := ed25519Manager.KeyPair() 854 ed25519Cert := createTestCertificate(t, ed25519Keys) 855 856 ed25519Filename := filepath.Join(tempDir, "ed25519_test.p12") 857 err = ToP12KeyPairFile(ed25519Keys, ed25519Cert, ed25519Filename, password) 858 if err != nil { 859 t.Errorf("Failed to create Ed25519 P12 file: %v", err) 860 } 861 862 // Verify file was created 863 if _, err := os.Stat(ed25519Filename); os.IsNotExist(err) { 864 t.Error("Ed25519 P12 file was not created") 865 } 866 }) 867 868 t.Run("FilePermissions", func(t *testing.T) { 869 filename := filepath.Join(tempDir, "permissions_test.p12") 870 err := ToP12KeyPairFile(rsaKeys, certificate, filename, password) 871 if err != nil { 872 t.Errorf("Failed to create P12 file: %v", err) 873 return 874 } 875 876 // Check file exists 877 fileInfo, err := os.Stat(filename) 878 if err != nil { 879 t.Errorf("Failed to stat P12 file: %v", err) 880 return 881 } 882 883 // Verify file has content 884 if fileInfo.Size() == 0 { 885 t.Error("P12 file should not be empty") 886 } 887 }) 888 889 t.Run("OverwriteExistingFile", func(t *testing.T) { 890 filename := filepath.Join(tempDir, "overwrite_test.p12") 891 892 // Create file first time 893 err := ToP12KeyPairFile(rsaKeys, certificate, filename, password) 894 if err != nil { 895 t.Errorf("Failed to create P12 file first time: %v", err) 896 return 897 } 898 899 // Get file info 900 firstInfo, err := os.Stat(filename) 901 if err != nil { 902 t.Errorf("Failed to stat first P12 file: %v", err) 903 return 904 } 905 906 // Wait a moment to ensure different timestamp 907 time.Sleep(10 * time.Millisecond) 908 909 // Overwrite the file 910 err = ToP12KeyPairFile(rsaKeys, certificate, filename, password) 911 if err != nil { 912 t.Errorf("Failed to overwrite P12 file: %v", err) 913 return 914 } 915 916 // Verify file was overwritten (check that it still exists) 917 secondInfo, err := os.Stat(filename) 918 if err != nil { 919 t.Errorf("Failed to stat overwritten P12 file: %v", err) 920 return 921 } 922 923 if secondInfo.Size() == 0 { 924 t.Error("Overwritten P12 file should not be empty") 925 } 926 927 // Files should have similar sizes (both contain the same key and cert) 928 sizeDiff := secondInfo.Size() - firstInfo.Size() 929 if sizeDiff < -100 || sizeDiff > 100 { 930 t.Errorf("Overwritten file size differs significantly: first=%d, second=%d", firstInfo.Size(), secondInfo.Size()) 931 } 932 }) 933 } 934 935 // TestConvertP12KeyPairToPEMErrorHandling tests error handling in ConvertP12KeyPairToPEM 936 func TestConvertP12KeyPairToPEMErrorHandling(t *testing.T) { 937 tempDir := t.TempDir() 938 password := "test123" 939 940 t.Run("NonExistentFile", func(t *testing.T) { 941 nonExistentFile := filepath.Join(tempDir, "nonexistent.p12") 942 privateKeyFile := filepath.Join(tempDir, "private.pem") 943 certFile := filepath.Join(tempDir, "cert.pem") 944 945 err := ConvertP12KeyPairToPEM(nonExistentFile, password, privateKeyFile, certFile) 946 if err == nil { 947 t.Error("Expected error when P12 file does not exist") 948 } 949 if err != nil && !contains(err.Error(), "failed to read P12 file") { 950 t.Errorf("Expected file read error, got: %v", err) 951 } 952 }) 953 954 t.Run("InvalidP12Data", func(t *testing.T) { 955 // Create a file with invalid P12 data 956 invalidP12File := filepath.Join(tempDir, "invalid.p12") 957 err := os.WriteFile(invalidP12File, []byte("this is not valid P12 data"), 0644) 958 if err != nil { 959 t.Fatalf("Failed to create invalid P12 file: %v", err) 960 } 961 962 privateKeyFile := filepath.Join(tempDir, "private_invalid.pem") 963 certFile := filepath.Join(tempDir, "cert_invalid.pem") 964 965 err = ConvertP12KeyPairToPEM(invalidP12File, password, privateKeyFile, certFile) 966 if err == nil { 967 t.Error("Expected error when P12 data is invalid") 968 } 969 if err != nil && !contains(err.Error(), "failed to load P12 with any key type") { 970 t.Errorf("Expected P12 load error, got: %v", err) 971 } 972 }) 973 974 t.Run("WrongPassword", func(t *testing.T) { 975 // First create a valid P12 file 976 manager, err := keypair.Generate[algo.KeySize, *algo.RSAKeyPair, *rsa.PrivateKey, *rsa.PublicKey](algo.KeySize2048) 977 if err != nil { 978 t.Fatalf("Failed to generate RSA keys: %v", err) 979 } 980 rsaKeys := manager.KeyPair() 981 certificate := createTestCertificate(t, rsaKeys) 982 983 p12File := filepath.Join(tempDir, "correct_password.p12") 984 err = ToP12KeyPairFile(rsaKeys, certificate, p12File, password) 985 if err != nil { 986 t.Fatalf("Failed to create P12 file: %v", err) 987 } 988 989 // Try to convert with wrong password 990 privateKeyFile := filepath.Join(tempDir, "private_wrong_pwd.pem") 991 certFile := filepath.Join(tempDir, "cert_wrong_pwd.pem") 992 993 err = ConvertP12KeyPairToPEM(p12File, "wrongpassword", privateKeyFile, certFile) 994 if err == nil { 995 t.Error("Expected error when using wrong password") 996 } 997 }) 998 999 t.Run("EmptyPrivateKeyFile", func(t *testing.T) { 1000 // Create a valid P12 file 1001 manager, err := keypair.Generate[algo.KeySize, *algo.RSAKeyPair, *rsa.PrivateKey, *rsa.PublicKey](algo.KeySize2048) 1002 if err != nil { 1003 t.Fatalf("Failed to generate RSA keys: %v", err) 1004 } 1005 rsaKeys := manager.KeyPair() 1006 certificate := createTestCertificate(t, rsaKeys) 1007 1008 p12File := filepath.Join(tempDir, "empty_private_key.p12") 1009 err = ToP12KeyPairFile(rsaKeys, certificate, p12File, password) 1010 if err != nil { 1011 t.Fatalf("Failed to create P12 file: %v", err) 1012 } 1013 1014 // Convert with empty private key file (should still work for cert only) 1015 certFile := filepath.Join(tempDir, "cert_only.pem") 1016 err = ConvertP12KeyPairToPEM(p12File, password, "", certFile) 1017 if err != nil { 1018 t.Errorf("Should be able to convert cert only: %v", err) 1019 } 1020 1021 // Verify cert file was created 1022 if _, err := os.Stat(certFile); os.IsNotExist(err) { 1023 t.Error("Certificate file was not created") 1024 } 1025 }) 1026 1027 t.Run("EmptyCertFile", func(t *testing.T) { 1028 // Create a valid P12 file 1029 manager, err := keypair.Generate[algo.KeySize, *algo.RSAKeyPair, *rsa.PrivateKey, *rsa.PublicKey](algo.KeySize2048) 1030 if err != nil { 1031 t.Fatalf("Failed to generate RSA keys: %v", err) 1032 } 1033 rsaKeys := manager.KeyPair() 1034 certificate := createTestCertificate(t, rsaKeys) 1035 1036 p12File := filepath.Join(tempDir, "empty_cert.p12") 1037 err = ToP12KeyPairFile(rsaKeys, certificate, p12File, password) 1038 if err != nil { 1039 t.Fatalf("Failed to create P12 file: %v", err) 1040 } 1041 1042 // Convert with empty cert file (should still work for key only) 1043 privateKeyFile := filepath.Join(tempDir, "private_only.pem") 1044 err = ConvertP12KeyPairToPEM(p12File, password, privateKeyFile, "") 1045 if err != nil { 1046 t.Errorf("Should be able to convert key only: %v", err) 1047 } 1048 1049 // Verify private key file was created 1050 if _, err := os.Stat(privateKeyFile); os.IsNotExist(err) { 1051 t.Error("Private key file was not created") 1052 } 1053 }) 1054 } 1055 1056 // Helper function to create a test certificate for a given key pair 1057 func createTestCertificate(t *testing.T, keyPair keypair.GenericKeyPair) *x509.Certificate { 1058 t.Helper() 1059 1060 template := &x509.Certificate{ 1061 Subject: pkix.Name{ 1062 CommonName: "Test Certificate", 1063 Organization: []string{"Test Org"}, 1064 Country: []string{"US"}, 1065 }, 1066 NotBefore: time.Now(), 1067 NotAfter: time.Now().Add(24 * time.Hour), 1068 KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment, 1069 ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageClientAuth}, 1070 SerialNumber: big.NewInt(1), 1071 } 1072 1073 var publicKey any 1074 var privateKey any 1075 1076 switch kp := keyPair.(type) { 1077 case *algo.RSAKeyPair: 1078 publicKey = kp.PublicKey 1079 privateKey = kp.PrivateKey 1080 case *algo.ECDSAKeyPair: 1081 publicKey = kp.PublicKey 1082 privateKey = kp.PrivateKey 1083 case *algo.Ed25519KeyPair: 1084 publicKey = kp.PublicKey 1085 privateKey = kp.PrivateKey 1086 default: 1087 t.Fatalf("Unsupported key pair type: %T", keyPair) 1088 return nil 1089 } 1090 1091 certDER, err := x509.CreateCertificate(rand.Reader, template, template, publicKey, privateKey) 1092 if err != nil { 1093 t.Fatalf("Failed to create certificate: %v", err) 1094 } 1095 1096 certificate, err := x509.ParseCertificate(certDER) 1097 if err != nil { 1098 t.Fatalf("Failed to parse certificate: %v", err) 1099 } 1100 1101 return certificate 1102 }