github.com/jasoet/gopki@v1.15.0/signing/signing_test.go (about) 1 package signing 2 3 import ( 4 "bytes" 5 "crypto" 6 "crypto/ecdsa" 7 "crypto/ed25519" 8 "crypto/rand" 9 "crypto/rsa" 10 "crypto/x509" 11 "crypto/x509/pkix" 12 "fmt" 13 "os" 14 "testing" 15 "time" 16 17 "github.com/jasoet/gopki/cert" 18 "github.com/jasoet/gopki/keypair" 19 "github.com/jasoet/gopki/keypair/algo" 20 ) 21 22 func TestSignAndVerifyRSA(t *testing.T) { 23 // Generate RSA key pair 24 manager, err := keypair.Generate[algo.KeySize, *algo.RSAKeyPair, *rsa.PrivateKey, *rsa.PublicKey](algo.KeySize2048) 25 if err != nil { 26 t.Fatalf("Failed to generate RSA key pair: %v", err) 27 } 28 keyPair := manager.KeyPair() 29 30 // Create a self-signed certificate 31 certificate, err := cert.CreateSelfSignedCertificate(keyPair, cert.CertificateRequest{ 32 Subject: pkix.Name{ 33 CommonName: "Test RSA Signer", 34 Organization: []string{"Test Org"}, 35 }, 36 DNSNames: []string{"test.example.com"}, 37 ValidFor: 365 * 24 * time.Hour, 38 }) 39 if err != nil { 40 t.Fatalf("Failed to create certificate: %v", err) 41 } 42 43 // Test data 44 testData := []byte("This is test data for RSA signing") 45 46 // Test different hash algorithms 47 hashAlgorithms := []crypto.Hash{ 48 crypto.SHA256, 49 crypto.SHA384, 50 crypto.SHA512, 51 } 52 53 for _, hashAlgo := range hashAlgorithms { 54 t.Run(HashAlgorithmToString(hashAlgo), func(t *testing.T) { 55 // Sign the data 56 opts := DefaultSignOptions() 57 opts.HashAlgorithm = hashAlgo 58 signature, err := SignDocument(testData, keyPair, certificate, opts) 59 if err != nil { 60 t.Fatalf("Failed to sign document: %v", err) 61 } 62 63 // Verify the signature 64 if signature.Algorithm != AlgorithmRSA { 65 t.Errorf("Expected algorithm %s, got %s", AlgorithmRSA, signature.Algorithm) 66 } 67 68 if signature.HashAlgorithm != hashAlgo { 69 t.Errorf("Expected hash algorithm %v, got %v", hashAlgo, signature.HashAlgorithm) 70 } 71 72 // Verify the signature 73 err = VerifySignature(testData, signature, DefaultVerifyOptions()) 74 if err != nil { 75 t.Errorf("Failed to verify signature: %v", err) 76 } 77 78 // Test with tampered data using detached signature for proper validation 79 detachedOpts := DefaultSignOptions() 80 detachedOpts.HashAlgorithm = hashAlgo 81 detachedOpts.Format = FormatPKCS7Detached 82 detachedSignature, err := SignDocument(testData, keyPair, certificate, detachedOpts) 83 if err != nil { 84 t.Fatalf("Failed to create detached signature: %v", err) 85 } 86 87 tamperedData := append(testData, byte('X')) 88 err = VerifySignature(tamperedData, detachedSignature, DefaultVerifyOptions()) 89 if err == nil { 90 t.Error("Expected verification to fail with tampered data") 91 } 92 }) 93 } 94 } 95 96 func TestSignAndVerifyECDSA(t *testing.T) { 97 curves := []algo.ECDSACurve{ 98 algo.P256, 99 algo.P384, 100 algo.P521, 101 } 102 103 for _, curve := range curves { 104 curveName := fmt.Sprintf("Curve_%d", curve) 105 t.Run(curveName, func(t *testing.T) { 106 // Generate ECDSA key pair 107 manager, err := keypair.Generate[algo.ECDSACurve, *algo.ECDSAKeyPair, *ecdsa.PrivateKey, *ecdsa.PublicKey](curve) 108 if err != nil { 109 t.Fatalf("Failed to generate ECDSA key pair: %v", err) 110 } 111 keyPair := manager.KeyPair() 112 if err != nil { 113 t.Fatalf("Failed to generate ECDSA key pair: %v", err) 114 } 115 116 // Create a self-signed certificate 117 certificate, err := cert.CreateSelfSignedCertificate(keyPair, cert.CertificateRequest{ 118 Subject: pkix.Name{ 119 CommonName: "Test ECDSA Signer", 120 Organization: []string{"Test Org"}, 121 }, 122 ValidFor: 365 * 24 * time.Hour, 123 }) 124 if err != nil { 125 t.Fatalf("Failed to create certificate: %v", err) 126 } 127 128 // Test data 129 testData := []byte("This is test data for ECDSA signing") 130 131 // Sign the data 132 signature, err := SignData(testData, keyPair, certificate) 133 if err != nil { 134 t.Fatalf("Failed to sign document: %v", err) 135 } 136 137 // Verify the signature 138 if signature.Algorithm != AlgorithmECDSA { 139 t.Errorf("Expected algorithm %s, got %s", AlgorithmECDSA, signature.Algorithm) 140 } 141 142 // Verify the signature 143 err = VerifySignature(testData, signature, DefaultVerifyOptions()) 144 if err != nil { 145 t.Errorf("Failed to verify signature: %v", err) 146 } 147 148 // Test with wrong data using detached signature for proper validation 149 detachedOpts := DefaultSignOptions() 150 detachedOpts.Format = FormatPKCS7Detached 151 detachedSignature, err := SignDocument(testData, keyPair, certificate, detachedOpts) 152 if err != nil { 153 t.Fatalf("Failed to create detached signature: %v", err) 154 } 155 156 wrongData := []byte("This is wrong data") 157 err = VerifySignature(wrongData, detachedSignature, DefaultVerifyOptions()) 158 if err == nil { 159 t.Error("Expected verification to fail with wrong data") 160 } 161 }) 162 } 163 } 164 165 func TestSignAndVerifyEd25519(t *testing.T) { 166 // Generate Ed25519 key pair 167 manager, err := keypair.Generate[algo.Ed25519Config, *algo.Ed25519KeyPair, ed25519.PrivateKey, ed25519.PublicKey]("") 168 if err != nil { 169 t.Fatalf("Failed to generate Ed25519 key pair: %v", err) 170 } 171 keyPair := manager.KeyPair() 172 if err != nil { 173 t.Fatalf("Failed to generate Ed25519 key pair: %v", err) 174 } 175 176 // Create a self-signed certificate 177 certificate, err := cert.CreateSelfSignedCertificate(keyPair, cert.CertificateRequest{ 178 Subject: pkix.Name{ 179 CommonName: "Test Ed25519 Signer", 180 Organization: []string{"Test Org"}, 181 }, 182 ValidFor: 365 * 24 * time.Hour, 183 }) 184 if err != nil { 185 t.Fatalf("Failed to create certificate: %v", err) 186 } 187 188 // Test data 189 testData := []byte("This is test data for Ed25519 signing") 190 191 // Sign the data 192 signature, err := SignData(testData, keyPair, certificate) 193 if err != nil { 194 t.Fatalf("Failed to sign document: %v", err) 195 } 196 197 // Verify the signature 198 if signature.Algorithm != AlgorithmEd25519 { 199 t.Errorf("Expected algorithm %s, got %s", AlgorithmEd25519, signature.Algorithm) 200 } 201 202 // Ed25519 should use SHA-512 203 if signature.HashAlgorithm != crypto.SHA512 { 204 t.Errorf("Expected hash algorithm SHA512 for Ed25519, got %v", signature.HashAlgorithm) 205 } 206 207 // Verify the signature 208 err = VerifySignature(testData, signature, DefaultVerifyOptions()) 209 if err != nil { 210 t.Errorf("Failed to verify signature: %v", err) 211 } 212 213 // Test with modified signature 214 signature.Data[0] ^= 0xFF 215 err = VerifySignature(testData, signature, DefaultVerifyOptions()) 216 if err == nil { 217 t.Error("Expected verification to fail with modified signature") 218 } 219 signature.Data[0] ^= 0xFF // Restore original 220 } 221 222 func TestCertificateValidation(t *testing.T) { 223 // Generate key pair 224 manager, err := keypair.Generate[algo.KeySize, *algo.RSAKeyPair, *rsa.PrivateKey, *rsa.PublicKey](algo.KeySize2048) 225 if err != nil { 226 t.Fatalf("Failed to generate RSA key pair: %v", err) 227 } 228 keyPair := manager.KeyPair() 229 if err != nil { 230 t.Fatalf("Failed to generate key pair: %v", err) 231 } 232 233 // Create an expired certificate 234 expiredCert, err := cert.CreateSelfSignedCertificate(keyPair, cert.CertificateRequest{ 235 Subject: pkix.Name{ 236 CommonName: "Expired Certificate", 237 }, 238 ValidFrom: time.Now().Add(-2 * 365 * 24 * time.Hour), // 2 years ago 239 ValidFor: 365 * 24 * time.Hour, // 1 year validity (now expired) 240 }) 241 if err != nil { 242 t.Fatalf("Failed to create expired certificate: %v", err) 243 } 244 245 // Test data 246 testData := []byte("Test data") 247 248 // Sign with expired certificate 249 signature, err := SignData(testData, keyPair, expiredCert) 250 if err != nil { 251 t.Fatalf("Failed to sign document: %v", err) 252 } 253 254 // Verify should fail due to expired certificate 255 err = VerifySignature(testData, signature, DefaultVerifyOptions()) 256 if err != ErrCertificateExpired { 257 t.Errorf("Expected ErrCertificateExpired, got %v", err) 258 } 259 } 260 261 func TestSigningOptions(t *testing.T) { 262 // Generate key pair 263 manager, err := keypair.Generate[algo.KeySize, *algo.RSAKeyPair, *rsa.PrivateKey, *rsa.PublicKey](algo.KeySize2048) 264 if err != nil { 265 t.Fatalf("Failed to generate RSA key pair: %v", err) 266 } 267 keyPair := manager.KeyPair() 268 if err != nil { 269 t.Fatalf("Failed to generate key pair: %v", err) 270 } 271 272 // Create certificate 273 certificate, err := cert.CreateSelfSignedCertificate(keyPair, cert.CertificateRequest{ 274 Subject: pkix.Name{ 275 CommonName: "Test Signer", 276 }, 277 ValidFor: 365 * 24 * time.Hour, 278 }) 279 if err != nil { 280 t.Fatalf("Failed to create certificate: %v", err) 281 } 282 283 testData := []byte("Test data for options") 284 285 t.Run("WithCertificate", func(t *testing.T) { 286 opts := DefaultSignOptions() 287 opts.IncludeCertificate = true 288 signature, err := SignDocument(testData, keyPair, certificate, opts) 289 if err != nil { 290 t.Fatalf("Failed to sign: %v", err) 291 } 292 293 if signature.Certificate == nil { 294 t.Error("Expected certificate to be included") 295 } 296 }) 297 298 t.Run("WithoutCertificate", func(t *testing.T) { 299 opts := DefaultSignOptions() 300 opts.IncludeCertificate = false 301 signature, err := SignDocument(testData, keyPair, certificate, opts) 302 if err != nil { 303 t.Fatalf("Failed to sign: %v", err) 304 } 305 306 if signature.Certificate != nil { 307 t.Error("Expected certificate not to be included") 308 } 309 310 // Verification should fail without certificate 311 err = VerifySignature(testData, signature, DefaultVerifyOptions()) 312 if err != ErrMissingCertificate { 313 t.Errorf("Expected ErrMissingCertificate, got %v", err) 314 } 315 316 // Verify with explicit certificate 317 err = VerifyWithCertificate(testData, signature, certificate.Certificate, DefaultVerifyOptions()) 318 if err != nil { 319 t.Errorf("Failed to verify with explicit certificate: %v", err) 320 } 321 }) 322 323 t.Run("WithMetadata", func(t *testing.T) { 324 opts := DefaultSignOptions() 325 opts.Attributes = map[string]interface{}{ 326 "author": "Test Author", 327 "timestamp": time.Now().Unix(), 328 "version": "1.0", 329 } 330 signature, err := SignDocument(testData, keyPair, certificate, opts) 331 if err != nil { 332 t.Fatalf("Failed to sign: %v", err) 333 } 334 335 if signature.Metadata == nil { 336 t.Error("Expected metadata to be included") 337 } 338 339 if author, ok := signature.Metadata["author"].(string); !ok || author != "Test Author" { 340 t.Error("Expected author metadata to be preserved") 341 } 342 }) 343 } 344 345 func TestCrossAlgorithmCompatibility(t *testing.T) { 346 // Test that different algorithms can coexist 347 algorithms := []struct { 348 name string 349 generate func() (interface{}, *cert.Certificate, error) 350 }{ 351 { 352 name: "RSA", 353 generate: func() (interface{}, *cert.Certificate, error) { 354 manager, err := keypair.Generate[algo.KeySize, *algo.RSAKeyPair, *rsa.PrivateKey, *rsa.PublicKey](algo.KeySize2048) 355 if err != nil { 356 t.Fatalf("Failed to generate RSA key pair: %v", err) 357 } 358 kp := manager.KeyPair() 359 if err != nil { 360 return nil, nil, err 361 } 362 c, err := cert.CreateSelfSignedCertificate(kp, cert.CertificateRequest{ 363 Subject: pkix.Name{CommonName: "RSA Test"}, 364 ValidFor: 365 * 24 * time.Hour, 365 }) 366 return kp, c, err 367 }, 368 }, 369 { 370 name: "ECDSA", 371 generate: func() (interface{}, *cert.Certificate, error) { 372 manager, err := keypair.Generate[algo.ECDSACurve, *algo.ECDSAKeyPair, *ecdsa.PrivateKey, *ecdsa.PublicKey](algo.P256) 373 if err != nil { 374 t.Fatalf("Failed to generate ECDSA key pair: %v", err) 375 } 376 kp := manager.KeyPair() 377 if err != nil { 378 return nil, nil, err 379 } 380 c, err := cert.CreateSelfSignedCertificate(kp, cert.CertificateRequest{ 381 Subject: pkix.Name{CommonName: "ECDSA Test"}, 382 ValidFor: 365 * 24 * time.Hour, 383 }) 384 return kp, c, err 385 }, 386 }, 387 { 388 name: "Ed25519", 389 generate: func() (interface{}, *cert.Certificate, error) { 390 manager, err := keypair.Generate[algo.Ed25519Config, *algo.Ed25519KeyPair, ed25519.PrivateKey, ed25519.PublicKey]("") 391 if err != nil { 392 t.Fatalf("Failed to generate Ed25519 key pair: %v", err) 393 } 394 kp := manager.KeyPair() 395 if err != nil { 396 return nil, nil, err 397 } 398 c, err := cert.CreateSelfSignedCertificate(kp, cert.CertificateRequest{ 399 Subject: pkix.Name{CommonName: "Ed25519 Test"}, 400 ValidFor: 365 * 24 * time.Hour, 401 }) 402 return kp, c, err 403 }, 404 }, 405 } 406 407 testData := []byte("Cross-algorithm test data") 408 var signatures []*Signature 409 410 // Sign with each algorithm 411 for _, alg := range algorithms { 412 t.Run("Sign_"+alg.name, func(t *testing.T) { 413 keyPair, certificate, err := alg.generate() 414 if err != nil { 415 t.Fatalf("Failed to generate %s keys: %v", alg.name, err) 416 } 417 418 var signature *Signature 419 switch kp := keyPair.(type) { 420 case *algo.RSAKeyPair: 421 signature, err = SignData(testData, kp, certificate) 422 case *algo.ECDSAKeyPair: 423 signature, err = SignData(testData, kp, certificate) 424 case *algo.Ed25519KeyPair: 425 signature, err = SignData(testData, kp, certificate) 426 } 427 428 if err != nil { 429 t.Fatalf("Failed to sign with %s: %v", alg.name, err) 430 } 431 432 signatures = append(signatures, signature) 433 }) 434 } 435 436 // Verify all signatures 437 for i, sig := range signatures { 438 t.Run("Verify_"+algorithms[i].name, func(t *testing.T) { 439 err := VerifySignature(testData, sig, DefaultVerifyOptions()) 440 if err != nil { 441 t.Errorf("Failed to verify %s signature: %v", algorithms[i].name, err) 442 } 443 }) 444 } 445 } 446 447 func TestSignatureInfo(t *testing.T) { 448 // Generate key pair 449 manager, err := keypair.Generate[algo.KeySize, *algo.RSAKeyPair, *rsa.PrivateKey, *rsa.PublicKey](algo.KeySize2048) 450 if err != nil { 451 t.Fatalf("Failed to generate RSA key pair: %v", err) 452 } 453 keyPair := manager.KeyPair() 454 if err != nil { 455 t.Fatalf("Failed to generate key pair: %v", err) 456 } 457 458 // Create certificate 459 certificate, err := cert.CreateSelfSignedCertificate(keyPair, cert.CertificateRequest{ 460 Subject: pkix.Name{ 461 CommonName: "Info Test", 462 Organization: []string{"Test Org"}, 463 Country: []string{"US"}, 464 }, 465 ValidFor: 365 * 24 * time.Hour, 466 }) 467 if err != nil { 468 t.Fatalf("Failed to create certificate: %v", err) 469 } 470 471 // Sign data 472 testData := []byte("Test data") 473 signature, err := SignData(testData, keyPair, certificate) 474 if err != nil { 475 t.Fatalf("Failed to sign: %v", err) 476 } 477 478 // Get signature info 479 info := GetSignatureInfo(signature) 480 if info == "" { 481 t.Error("Expected signature info to be non-empty") 482 } 483 484 // Check that info contains expected elements 485 expectedStrings := []string{ 486 "Algorithm: RSA", 487 "Hash: SHA256", 488 "Signer: Info Test", 489 } 490 491 for _, expected := range expectedStrings { 492 if !contains(info, expected) { 493 t.Errorf("Expected info to contain '%s'", expected) 494 } 495 } 496 497 // Test IsSignatureValid 498 if !IsSignatureValid(signature) { 499 t.Error("Expected signature to be valid") 500 } 501 502 // Test with nil signature 503 if IsSignatureValid(nil) { 504 t.Error("Expected nil signature to be invalid") 505 } 506 507 // Test with empty signature data 508 emptySignature := &Signature{ 509 Algorithm: AlgorithmRSA, 510 HashAlgorithm: crypto.SHA256, 511 Data: []byte{}, 512 } 513 if IsSignatureValid(emptySignature) { 514 t.Error("Expected signature with empty data to be invalid") 515 } 516 } 517 518 // Helper function to check if a string contains a substring 519 func contains(s, substr string) bool { 520 return len(s) > 0 && len(substr) > 0 && len(s) >= len(substr) && 521 (s == substr || len(s) > len(substr) && (s[:len(substr)] == substr || contains(s[1:], substr))) 522 } 523 524 // TestSignFile tests the SignFile function 525 func TestSignFile(t *testing.T) { 526 // Generate RSA key pair 527 manager, err := keypair.Generate[algo.KeySize, *algo.RSAKeyPair, *rsa.PrivateKey, *rsa.PublicKey](algo.KeySize2048) 528 if err != nil { 529 t.Fatalf("Failed to generate RSA key pair: %v", err) 530 } 531 keyPair := manager.KeyPair() 532 if err != nil { 533 t.Fatalf("Failed to generate RSA key pair: %v", err) 534 } 535 536 // Create a self-signed certificate 537 certificate, err := cert.CreateSelfSignedCertificate(keyPair, cert.CertificateRequest{ 538 Subject: pkix.Name{ 539 CommonName: "Test File Signer", 540 }, 541 ValidFor: 24 * time.Hour, 542 }) 543 if err != nil { 544 t.Fatalf("Failed to create certificate: %v", err) 545 } 546 547 // Create a temporary test file 548 testData := []byte("This is test data for file signing") 549 testFile := "/tmp/gopki_test_file.txt" 550 551 err = os.WriteFile(testFile, testData, 0644) 552 if err != nil { 553 t.Fatalf("Failed to write test file: %v", err) 554 } 555 defer os.Remove(testFile) // Clean up 556 557 // Test signing the file 558 opts := DefaultSignOptions() 559 opts.HashAlgorithm = crypto.SHA256 560 561 signature, err := SignFile(testFile, keyPair, certificate, opts) 562 if err != nil { 563 t.Fatalf("Failed to sign file: %v", err) 564 } 565 566 // Verify signature properties 567 if signature.Algorithm != AlgorithmRSA { 568 t.Errorf("Expected algorithm %s, got %s", AlgorithmRSA, signature.Algorithm) 569 } 570 571 if signature.HashAlgorithm != crypto.SHA256 { 572 t.Errorf("Expected hash algorithm SHA256, got %v", signature.HashAlgorithm) 573 } 574 575 if len(signature.Data) == 0 { 576 t.Error("Expected signature data to be non-empty") 577 } 578 579 // Verify the signature by comparing with direct SignDocument 580 directSignature, err := SignDocument(testData, keyPair, certificate, opts) 581 if err != nil { 582 t.Fatalf("Failed to sign data directly: %v", err) 583 } 584 585 // The signatures should be the same (assuming deterministic signing) 586 if len(signature.Data) != len(directSignature.Data) { 587 t.Errorf("Expected same signature length: file=%d, direct=%d", 588 len(signature.Data), len(directSignature.Data)) 589 } 590 591 // Test with non-existent file 592 _, err = SignFile("/non/existent/file.txt", keyPair, certificate, opts) 593 if err == nil { 594 t.Error("Expected error when signing non-existent file") 595 } 596 } 597 598 // TestSignStream tests the SignStream function 599 func TestSignStream(t *testing.T) { 600 // Generate ECDSA key pair for variety 601 manager, err := keypair.Generate[algo.ECDSACurve, *algo.ECDSAKeyPair, *ecdsa.PrivateKey, *ecdsa.PublicKey](algo.P256) 602 if err != nil { 603 t.Fatalf("Failed to generate ECDSA key pair: %v", err) 604 } 605 keyPair := manager.KeyPair() 606 607 // Create a self-signed certificate 608 certificate, err := cert.CreateSelfSignedCertificate(keyPair, cert.CertificateRequest{ 609 Subject: pkix.Name{ 610 CommonName: "Test Stream Signer", 611 }, 612 ValidFor: 24 * time.Hour, 613 }) 614 if err != nil { 615 t.Fatalf("Failed to create certificate: %v", err) 616 } 617 618 testData := []byte("This is test data for stream signing with ECDSA") 619 620 // Test signing from a stream 621 opts := DefaultSignOptions() 622 opts.HashAlgorithm = crypto.SHA256 623 624 reader := bytes.NewReader(testData) 625 signature, err := SignStream(reader, keyPair, certificate, opts) 626 if err != nil { 627 t.Fatalf("Failed to sign stream: %v", err) 628 } 629 630 // Verify signature properties 631 if signature.Algorithm != AlgorithmECDSA { 632 t.Errorf("Expected algorithm %s, got %s", AlgorithmECDSA, signature.Algorithm) 633 } 634 635 if signature.HashAlgorithm != crypto.SHA256 { 636 t.Errorf("Expected hash algorithm SHA256, got %v", signature.HashAlgorithm) 637 } 638 639 if len(signature.Data) == 0 { 640 t.Error("Expected signature data to be non-empty") 641 } 642 643 // Verify digest matches direct computation 644 directSignature, err := SignDocument(testData, keyPair, certificate, opts) 645 if err != nil { 646 t.Fatalf("Failed to sign data directly: %v", err) 647 } 648 649 // The digests should be the same 650 if !bytes.Equal(signature.Digest, directSignature.Digest) { 651 t.Error("Expected stream and direct signing to produce same digest") 652 } 653 654 // Test with Ed25519 for different code path 655 ed25519Manager, err := keypair.Generate[algo.Ed25519Config, *algo.Ed25519KeyPair, ed25519.PrivateKey, ed25519.PublicKey]("") 656 if err != nil { 657 t.Fatalf("Failed to generate Ed25519 key pair: %v", err) 658 } 659 ed25519KeyPair := ed25519Manager.KeyPair() 660 if err != nil { 661 t.Fatalf("Failed to generate Ed25519 key pair: %v", err) 662 } 663 664 ed25519Cert, err := cert.CreateSelfSignedCertificate(ed25519KeyPair, cert.CertificateRequest{ 665 Subject: pkix.Name{ 666 CommonName: "Test Ed25519 Stream Signer", 667 }, 668 ValidFor: 24 * time.Hour, 669 }) 670 if err != nil { 671 t.Fatalf("Failed to create Ed25519 certificate: %v", err) 672 } 673 674 reader2 := bytes.NewReader(testData) 675 ed25519Signature, err := SignStream(reader2, ed25519KeyPair, ed25519Cert, opts) 676 if err != nil { 677 t.Fatalf("Failed to sign stream with Ed25519: %v", err) 678 } 679 680 if ed25519Signature.Algorithm != AlgorithmEd25519 { 681 t.Errorf("Expected Ed25519 algorithm, got %s", ed25519Signature.Algorithm) 682 } 683 684 // Test with empty stream 685 emptyReader := bytes.NewReader([]byte{}) 686 _, err = SignStream(emptyReader, keyPair, certificate, opts) 687 if err != nil { 688 t.Logf("Signing empty stream returned error (expected): %v", err) 689 } 690 } 691 692 // TestGetSignatureAlgorithm tests the GetSignatureAlgorithm function 693 func TestGetSignatureAlgorithm(t *testing.T) { 694 // Test with RSA key 695 rsaManager, err := keypair.Generate[algo.KeySize, *algo.RSAKeyPair, *rsa.PrivateKey, *rsa.PublicKey](algo.KeySize2048) 696 if err != nil { 697 t.Fatalf("Failed to generate RSA key pair: %v", err) 698 } 699 rsaKeyPair := rsaManager.KeyPair() 700 if err != nil { 701 t.Fatalf("Failed to generate RSA key pair: %v", err) 702 } 703 704 alg, err := GetSignatureAlgorithm(rsaKeyPair.PublicKey) 705 if err != nil { 706 t.Fatalf("Failed to get RSA algorithm: %v", err) 707 } 708 if alg != AlgorithmRSA { 709 t.Errorf("Expected RSA algorithm, got %s", alg) 710 } 711 712 // Test with ECDSA key 713 ecdsaManager, err := keypair.Generate[algo.ECDSACurve, *algo.ECDSAKeyPair, *ecdsa.PrivateKey, *ecdsa.PublicKey](algo.P256) 714 if err != nil { 715 t.Fatalf("Failed to generate ECDSA key pair: %v", err) 716 } 717 ecdsaKeyPair := ecdsaManager.KeyPair() 718 if err != nil { 719 t.Fatalf("Failed to generate ECDSA key pair: %v", err) 720 } 721 722 alg, err = GetSignatureAlgorithm(ecdsaKeyPair.PublicKey) 723 if err != nil { 724 t.Fatalf("Failed to get ECDSA algorithm: %v", err) 725 } 726 if alg != AlgorithmECDSA { 727 t.Errorf("Expected ECDSA algorithm, got %s", alg) 728 } 729 730 // Test with Ed25519 key 731 ed25519Manager, err := keypair.Generate[algo.Ed25519Config, *algo.Ed25519KeyPair, ed25519.PrivateKey, ed25519.PublicKey]("") 732 if err != nil { 733 t.Fatalf("Failed to generate Ed25519 key pair: %v", err) 734 } 735 ed25519KeyPair := ed25519Manager.KeyPair() 736 if err != nil { 737 t.Fatalf("Failed to generate Ed25519 key pair: %v", err) 738 } 739 740 alg, err = GetSignatureAlgorithm(ed25519KeyPair.PublicKey) 741 if err != nil { 742 t.Fatalf("Failed to get Ed25519 algorithm: %v", err) 743 } 744 if alg != AlgorithmEd25519 { 745 t.Errorf("Expected Ed25519 algorithm, got %s", alg) 746 } 747 748 // Test with unsupported key type (string as placeholder) 749 _, err = GetSignatureAlgorithm("unsupported key type") 750 if err == nil { 751 t.Error("Expected error for unsupported key type") 752 } 753 } 754 755 // TestComputeDigest tests the ComputeDigest function 756 func TestComputeDigest(t *testing.T) { 757 testData := []byte("This is test data for digest computation") 758 759 // Test SHA256 760 digest, err := ComputeDigest(testData, crypto.SHA256) 761 if err != nil { 762 t.Fatalf("Failed to compute SHA256 digest: %v", err) 763 } 764 if len(digest) != 32 { // SHA256 produces 32-byte hash 765 t.Errorf("Expected SHA256 digest length 32, got %d", len(digest)) 766 } 767 768 // Test SHA384 769 digest384, err := ComputeDigest(testData, crypto.SHA384) 770 if err != nil { 771 t.Fatalf("Failed to compute SHA384 digest: %v", err) 772 } 773 if len(digest384) != 48 { // SHA384 produces 48-byte hash 774 t.Errorf("Expected SHA384 digest length 48, got %d", len(digest384)) 775 } 776 777 // Test SHA512 778 digest512, err := ComputeDigest(testData, crypto.SHA512) 779 if err != nil { 780 t.Fatalf("Failed to compute SHA512 digest: %v", err) 781 } 782 if len(digest512) != 64 { // SHA512 produces 64-byte hash 783 t.Errorf("Expected SHA512 digest length 64, got %d", len(digest512)) 784 } 785 786 // Test that same data produces same digest 787 digest2, err := ComputeDigest(testData, crypto.SHA256) 788 if err != nil { 789 t.Fatalf("Failed to compute second SHA256 digest: %v", err) 790 } 791 if !bytes.Equal(digest, digest2) { 792 t.Error("Expected same data to produce same digest") 793 } 794 795 // Test with empty data 796 emptyDigest, err := ComputeDigest([]byte{}, crypto.SHA256) 797 if err != nil { 798 t.Fatalf("Failed to compute digest of empty data: %v", err) 799 } 800 if len(emptyDigest) != 32 { 801 t.Errorf("Expected empty data SHA256 digest length 32, got %d", len(emptyDigest)) 802 } 803 804 // Test with unavailable hash (this is tricky since most are available) 805 // We'll test with a hypothetical unavailable hash by using a very high number 806 _, err = ComputeDigest(testData, crypto.Hash(999)) 807 if err == nil { 808 t.Error("Expected error for unavailable hash algorithm") 809 } 810 } 811 812 // TestHashAlgorithmFromString tests the HashAlgorithmFromString function 813 func TestHashAlgorithmFromString(t *testing.T) { 814 tests := []struct { 815 input string 816 expected crypto.Hash 817 }{ 818 {"SHA256", crypto.SHA256}, 819 {"SHA384", crypto.SHA384}, 820 {"SHA512", crypto.SHA512}, 821 {"SHA224", crypto.SHA224}, 822 {"unknown", crypto.SHA256}, // Should default to SHA256 823 {"", crypto.SHA256}, // Should default to SHA256 824 {"sha256", crypto.SHA256}, // Should default to SHA256 (case sensitive) 825 } 826 827 for _, test := range tests { 828 t.Run(fmt.Sprintf("input_%s", test.input), func(t *testing.T) { 829 result := HashAlgorithmFromString(test.input) 830 if result != test.expected { 831 t.Errorf("Expected %v for input %q, got %v", test.expected, test.input, result) 832 } 833 }) 834 } 835 } 836 837 // TestHashAlgorithmToString tests the HashAlgorithmToString function (already used in other tests) 838 func TestHashAlgorithmToString(t *testing.T) { 839 tests := []struct { 840 input crypto.Hash 841 expected string 842 }{ 843 {crypto.SHA256, "SHA256"}, 844 {crypto.SHA384, "SHA384"}, 845 {crypto.SHA512, "SHA512"}, 846 {crypto.SHA224, "SHA224"}, 847 {crypto.Hash(999), "Unknown"}, // Unsupported hash 848 } 849 850 for _, test := range tests { 851 t.Run(fmt.Sprintf("hash_%d", int(test.input)), func(t *testing.T) { 852 result := HashAlgorithmToString(test.input) 853 if result != test.expected { 854 t.Errorf("Expected %q for hash %v, got %q", test.expected, test.input, result) 855 } 856 }) 857 } 858 } 859 860 // TestGetHashAlgorithm tests the GetHashAlgorithm function 861 func TestGetHashAlgorithm(t *testing.T) { 862 tests := []struct { 863 name string 864 algorithm SignatureAlgorithm 865 keySize int 866 want crypto.Hash 867 }{ 868 // RSA tests 869 { 870 name: "RSA 2048-bit key", 871 algorithm: AlgorithmRSA, 872 keySize: 2048, 873 want: crypto.SHA256, 874 }, 875 { 876 name: "RSA 3072-bit key", 877 algorithm: AlgorithmRSA, 878 keySize: 3072, 879 want: crypto.SHA384, 880 }, 881 { 882 name: "RSA 4096-bit key", 883 algorithm: AlgorithmRSA, 884 keySize: 4096, 885 want: crypto.SHA384, 886 }, 887 // ECDSA tests 888 { 889 name: "ECDSA P-256 (256-bit)", 890 algorithm: AlgorithmECDSA, 891 keySize: 256, 892 want: crypto.SHA256, 893 }, 894 { 895 name: "ECDSA P-384 (384-bit)", 896 algorithm: AlgorithmECDSA, 897 keySize: 384, 898 want: crypto.SHA384, 899 }, 900 { 901 name: "ECDSA P-521 (521-bit)", 902 algorithm: AlgorithmECDSA, 903 keySize: 521, 904 want: crypto.SHA384, // keySize >= 384 returns SHA384 905 }, 906 // Ed25519 tests 907 { 908 name: "Ed25519", 909 algorithm: AlgorithmEd25519, 910 keySize: 256, // Ed25519 has fixed key size 911 want: crypto.SHA512, 912 }, 913 // Default cases 914 { 915 name: "Unknown algorithm", 916 algorithm: SignatureAlgorithm("UNKNOWN"), 917 keySize: 2048, 918 want: crypto.SHA256, // Falls back to default 919 }, 920 { 921 name: "RSA with small keysize", 922 algorithm: AlgorithmRSA, 923 keySize: 1024, 924 want: crypto.SHA256, 925 }, 926 { 927 name: "ECDSA with non-standard size", 928 algorithm: AlgorithmECDSA, 929 keySize: 224, 930 want: crypto.SHA256, // Default for P-224 931 }, 932 } 933 934 for _, tt := range tests { 935 t.Run(tt.name, func(t *testing.T) { 936 got := GetHashAlgorithm(tt.algorithm, tt.keySize) 937 if got != tt.want { 938 t.Errorf("GetHashAlgorithm() = %v, want %v", got, tt.want) 939 } 940 }) 941 } 942 } 943 944 // TestSignData tests the convenience SignData function 945 func TestSignData(t *testing.T) { 946 // Generate RSA key pair 947 manager, err := keypair.Generate[algo.KeySize, *algo.RSAKeyPair, *rsa.PrivateKey, *rsa.PublicKey](algo.KeySize2048) 948 if err != nil { 949 t.Fatalf("Failed to generate RSA key pair: %v", err) 950 } 951 keyPair := manager.KeyPair() 952 if err != nil { 953 t.Fatalf("Failed to generate RSA key pair: %v", err) 954 } 955 956 // Create a self-signed certificate 957 certificate, err := cert.CreateSelfSignedCertificate(keyPair, cert.CertificateRequest{ 958 Subject: pkix.Name{ 959 CommonName: "Test Data Signer", 960 }, 961 ValidFor: 24 * time.Hour, 962 }) 963 if err != nil { 964 t.Fatalf("Failed to create certificate: %v", err) 965 } 966 967 testData := []byte("This is test data for convenience SignData function") 968 969 // Test the convenience function 970 signature, err := SignData(testData, keyPair, certificate) 971 if err != nil { 972 t.Fatalf("Failed to sign data with convenience function: %v", err) 973 } 974 975 // Should use default options 976 if signature.Format != FormatPKCS7 { 977 t.Errorf("Expected default format %s, got %s", FormatPKCS7, signature.Format) 978 } 979 980 if signature.Algorithm != AlgorithmRSA { 981 t.Errorf("Expected RSA algorithm, got %s", signature.Algorithm) 982 } 983 984 if len(signature.Data) == 0 { 985 t.Error("Expected signature data to be non-empty") 986 } 987 988 // Should include certificate by default 989 if signature.Certificate == nil { 990 t.Error("Expected certificate to be included by default") 991 } 992 } 993 994 // TestVerifyECDSASignature tests the verifyECDSASignature function (0% coverage) 995 func TestVerifyECDSASignature(t *testing.T) { 996 // Generate ECDSA key pair 997 ecdsaManager, err := keypair.Generate[algo.ECDSACurve, *algo.ECDSAKeyPair, *ecdsa.PrivateKey, *ecdsa.PublicKey](algo.P256) 998 if err != nil { 999 t.Fatalf("Failed to generate ECDSA key pair: %v", err) 1000 } 1001 ecdsaKeyPair := ecdsaManager.KeyPair() 1002 1003 // Create certificate 1004 ecdsaCert, err := cert.CreateSelfSignedCertificate(ecdsaKeyPair, cert.CertificateRequest{ 1005 Subject: pkix.Name{ 1006 CommonName: "Test ECDSA Verifier", 1007 }, 1008 ValidFor: 24 * time.Hour, 1009 }) 1010 if err != nil { 1011 t.Fatalf("Failed to create ECDSA certificate: %v", err) 1012 } 1013 1014 testData := []byte("Test data for ECDSA verification") 1015 1016 // Create signature 1017 signature, err := SignDocument(testData, ecdsaKeyPair, ecdsaCert, SignOptions{ 1018 HashAlgorithm: crypto.SHA256, 1019 Format: FormatPKCS7Detached, 1020 IncludeCertificate: true, 1021 }) 1022 if err != nil { 1023 t.Fatalf("Failed to create ECDSA signature: %v", err) 1024 } 1025 1026 // Test successful verification 1027 err = VerifySignature(testData, signature, DefaultVerifyOptions()) 1028 if err != nil { 1029 t.Errorf("ECDSA signature verification should succeed: %v", err) 1030 } 1031 1032 // Test with wrong data 1033 wrongData := []byte("Wrong data") 1034 err = VerifySignature(wrongData, signature, DefaultVerifyOptions()) 1035 if err == nil { 1036 t.Error("ECDSA verification should fail with wrong data") 1037 } 1038 1039 // Test with corrupted signature 1040 corruptedSig := &Signature{ 1041 Algorithm: signature.Algorithm, 1042 HashAlgorithm: signature.HashAlgorithm, 1043 Data: append([]byte{0xFF}, signature.Data...), 1044 Certificate: signature.Certificate, 1045 } 1046 err = VerifySignature(testData, corruptedSig, DefaultVerifyOptions()) 1047 if err == nil { 1048 t.Error("ECDSA verification should fail with corrupted signature") 1049 } 1050 } 1051 1052 // TestVerifyEd25519Signature tests the verifyEd25519Signature function (0% coverage) 1053 func TestVerifyEd25519Signature(t *testing.T) { 1054 // Generate Ed25519 key pair 1055 ed25519Manager, err := keypair.Generate[algo.Ed25519Config, *algo.Ed25519KeyPair, ed25519.PrivateKey, ed25519.PublicKey]("") 1056 if err != nil { 1057 t.Fatalf("Failed to generate Ed25519 key pair: %v", err) 1058 } 1059 ed25519KeyPair := ed25519Manager.KeyPair() 1060 1061 // Create certificate 1062 ed25519Cert, err := cert.CreateSelfSignedCertificate(ed25519KeyPair, cert.CertificateRequest{ 1063 Subject: pkix.Name{ 1064 CommonName: "Test Ed25519 Verifier", 1065 }, 1066 ValidFor: 24 * time.Hour, 1067 }) 1068 if err != nil { 1069 t.Fatalf("Failed to create Ed25519 certificate: %v", err) 1070 } 1071 1072 testData := []byte("Test data for Ed25519 verification") 1073 1074 // Create signature 1075 signature, err := SignDocument(testData, ed25519KeyPair, ed25519Cert, SignOptions{ 1076 HashAlgorithm: crypto.SHA512, 1077 Format: FormatPKCS7, 1078 IncludeCertificate: true, 1079 }) 1080 if err != nil { 1081 t.Fatalf("Failed to create Ed25519 signature: %v", err) 1082 } 1083 1084 // Test successful verification 1085 err = VerifySignature(testData, signature, DefaultVerifyOptions()) 1086 if err != nil { 1087 t.Errorf("Ed25519 signature verification should succeed: %v", err) 1088 } 1089 1090 // Test with wrong data 1091 wrongData := []byte("Wrong data for Ed25519") 1092 err = VerifySignature(wrongData, signature, DefaultVerifyOptions()) 1093 if err == nil { 1094 t.Error("Ed25519 verification should fail with wrong data") 1095 } 1096 1097 // Test with corrupted signature 1098 corruptedSig := &Signature{ 1099 Algorithm: signature.Algorithm, 1100 HashAlgorithm: signature.HashAlgorithm, 1101 Data: append([]byte{0xFF}, signature.Data...), 1102 Certificate: signature.Certificate, 1103 } 1104 err = VerifySignature(testData, corruptedSig, DefaultVerifyOptions()) 1105 if err == nil { 1106 t.Error("Ed25519 verification should fail with corrupted signature") 1107 } 1108 } 1109 1110 // TestVerifyDetachedSignature tests the VerifyDetachedSignature function (0% coverage) 1111 func TestVerifyDetachedSignature(t *testing.T) { 1112 // Generate RSA key pair for testing 1113 rsaManager, err := keypair.Generate[algo.KeySize, *algo.RSAKeyPair, *rsa.PrivateKey, *rsa.PublicKey](algo.KeySize2048) 1114 if err != nil { 1115 t.Fatalf("Failed to generate RSA key pair: %v", err) 1116 } 1117 rsaKeyPair := rsaManager.KeyPair() 1118 1119 // Create certificate 1120 rsaCert, err := cert.CreateSelfSignedCertificate(rsaKeyPair, cert.CertificateRequest{ 1121 Subject: pkix.Name{ 1122 CommonName: "Test Detached Signer", 1123 }, 1124 ValidFor: 24 * time.Hour, 1125 }) 1126 if err != nil { 1127 t.Fatalf("Failed to create RSA certificate: %v", err) 1128 } 1129 1130 testData := []byte("Test data for detached signature verification") 1131 1132 // Create a raw signature for detached verification 1133 // First compute the hash 1134 hasher := crypto.SHA256.New() 1135 hasher.Write(testData) 1136 digest := hasher.Sum(nil) 1137 1138 // Sign the digest directly 1139 rawSigBytes, err := rsaKeyPair.PrivateKey.Sign(rand.Reader, digest, crypto.SHA256) 1140 if err != nil { 1141 t.Fatalf("Failed to create raw signature: %v", err) 1142 } 1143 1144 // Test successful detached verification 1145 err = VerifyDetachedSignature(testData, rawSigBytes, rsaCert.Certificate, crypto.SHA256) 1146 if err != nil { 1147 t.Errorf("Detached signature verification should succeed: %v", err) 1148 } 1149 1150 // Test with wrong data 1151 wrongData := []byte("Wrong data for detached") 1152 err = VerifyDetachedSignature(wrongData, rawSigBytes, rsaCert.Certificate, crypto.SHA256) 1153 if err == nil { 1154 t.Error("Detached verification should fail with wrong data") 1155 } 1156 1157 // Test with nil certificate 1158 err = VerifyDetachedSignature(testData, rawSigBytes, nil, crypto.SHA256) 1159 if err == nil { 1160 t.Error("Detached verification should fail with nil certificate") 1161 } 1162 1163 // Test with wrong hash algorithm 1164 err = VerifyDetachedSignature(testData, rawSigBytes, rsaCert.Certificate, crypto.SHA512) 1165 if err == nil { 1166 t.Error("Detached verification should fail with wrong hash algorithm") 1167 } 1168 1169 // Test with ECDSA 1170 ecdsaManager, err := keypair.Generate[algo.ECDSACurve, *algo.ECDSAKeyPair, *ecdsa.PrivateKey, *ecdsa.PublicKey](algo.P256) 1171 if err != nil { 1172 t.Fatalf("Failed to generate ECDSA key pair: %v", err) 1173 } 1174 ecdsaKeyPair := ecdsaManager.KeyPair() 1175 1176 ecdsaCert, err := cert.CreateSelfSignedCertificate(ecdsaKeyPair, cert.CertificateRequest{ 1177 Subject: pkix.Name{ 1178 CommonName: "Test ECDSA Detached Signer", 1179 }, 1180 ValidFor: 24 * time.Hour, 1181 }) 1182 if err != nil { 1183 t.Fatalf("Failed to create ECDSA certificate: %v", err) 1184 } 1185 1186 // Create ECDSA raw signature for detached verification 1187 ecdsaHasher := crypto.SHA256.New() 1188 ecdsaHasher.Write(testData) 1189 ecdsaDigest := ecdsaHasher.Sum(nil) 1190 1191 ecdsaRawSigBytes, err := ecdsaKeyPair.PrivateKey.Sign(rand.Reader, ecdsaDigest, crypto.SHA256) 1192 if err != nil { 1193 t.Fatalf("Failed to create ECDSA raw signature: %v", err) 1194 } 1195 1196 err = VerifyDetachedSignature(testData, ecdsaRawSigBytes, ecdsaCert.Certificate, crypto.SHA256) 1197 if err != nil { 1198 t.Errorf("ECDSA detached signature verification should succeed: %v", err) 1199 } 1200 } 1201 1202 // TestVerifyCertificateChain tests the verifyCertificateChain function (0% coverage) 1203 func TestVerifyCertificateChain(t *testing.T) { 1204 // Create root CA 1205 rootCAManager, err := keypair.Generate[algo.KeySize, *algo.RSAKeyPair, *rsa.PrivateKey, *rsa.PublicKey](algo.KeySize2048) 1206 if err != nil { 1207 t.Fatalf("Failed to generate root CA key pair: %v", err) 1208 } 1209 rootCAKeyPair := rootCAManager.KeyPair() 1210 1211 rootCACert, err := cert.CreateCACertificate(rootCAKeyPair, cert.CertificateRequest{ 1212 Subject: pkix.Name{ 1213 CommonName: "Test Root CA", 1214 Organization: []string{"Test Org"}, 1215 Country: []string{"US"}, 1216 }, 1217 ValidFor: 365 * 24 * time.Hour, 1218 }) 1219 if err != nil { 1220 t.Fatalf("Failed to create root CA certificate: %v", err) 1221 } 1222 1223 // Create end-entity certificate signed by root CA 1224 endEntityManager, err := keypair.Generate[algo.KeySize, *algo.RSAKeyPair, *rsa.PrivateKey, *rsa.PublicKey](algo.KeySize2048) 1225 if err != nil { 1226 t.Fatalf("Failed to generate end-entity key pair: %v", err) 1227 } 1228 endEntityKeyPair := endEntityManager.KeyPair() 1229 1230 endEntityCert, err := cert.SignCertificate(rootCACert, rootCAKeyPair, cert.CertificateRequest{ 1231 Subject: pkix.Name{ 1232 CommonName: "Test End Entity", 1233 }, 1234 ValidFor: 30 * 24 * time.Hour, 1235 }, endEntityKeyPair.PublicKey) 1236 if err != nil { 1237 t.Fatalf("Failed to create end-entity certificate: %v", err) 1238 } 1239 1240 // Test certificate chain verification through signature verification 1241 testData := []byte("Test data for certificate chain verification") 1242 1243 signature, err := SignDocument(testData, endEntityKeyPair, endEntityCert, SignOptions{ 1244 HashAlgorithm: crypto.SHA256, 1245 Format: FormatPKCS7, 1246 IncludeCertificate: true, 1247 }) 1248 if err != nil { 1249 t.Fatalf("Failed to create signature: %v", err) 1250 } 1251 1252 // No intermediate certificates needed for direct root CA signing 1253 1254 // Create root certificate pool 1255 rootPool := x509.NewCertPool() 1256 rootPool.AddCert(rootCACert.Certificate) 1257 1258 // Test successful chain verification 1259 verifyOpts := VerifyOptions{ 1260 VerifyChain: true, 1261 Roots: rootPool, 1262 } 1263 1264 err = VerifySignature(testData, signature, verifyOpts) 1265 if err != nil { 1266 t.Errorf("Certificate chain verification should succeed: %v", err) 1267 } 1268 1269 // Test chain verification failure with wrong root 1270 wrongRootManager, err := keypair.Generate[algo.KeySize, *algo.RSAKeyPair, *rsa.PrivateKey, *rsa.PublicKey](algo.KeySize2048) 1271 if err != nil { 1272 t.Fatalf("Failed to generate wrong root key pair: %v", err) 1273 } 1274 wrongRootKeyPair := wrongRootManager.KeyPair() 1275 1276 wrongRootCert, err := cert.CreateCACertificate(wrongRootKeyPair, cert.CertificateRequest{ 1277 Subject: pkix.Name{ 1278 CommonName: "Wrong Root CA", 1279 }, 1280 ValidFor: 365 * 24 * time.Hour, 1281 }) 1282 if err != nil { 1283 t.Fatalf("Failed to create wrong root CA certificate: %v", err) 1284 } 1285 1286 wrongRootPool := x509.NewCertPool() 1287 wrongRootPool.AddCert(wrongRootCert.Certificate) 1288 1289 wrongVerifyOpts := VerifyOptions{ 1290 VerifyChain: true, 1291 Roots: wrongRootPool, 1292 } 1293 1294 err = VerifySignature(testData, signature, wrongVerifyOpts) 1295 if err == nil { 1296 t.Error("Certificate chain verification should fail with wrong root") 1297 } 1298 1299 // Test without chain verification (should succeed) 1300 noChainOpts := DefaultVerifyOptions() 1301 noChainOpts.VerifyChain = false 1302 1303 err = VerifySignature(testData, signature, noChainOpts) 1304 if err != nil { 1305 t.Errorf("Signature verification without chain check should succeed: %v", err) 1306 } 1307 } 1308 1309 // TestVerifyTimestamp tests the VerifyTimestamp function (0% coverage) 1310 func TestVerifyTimestamp(t *testing.T) { 1311 // Generate key pair for signature 1312 manager, err := keypair.Generate[algo.KeySize, *algo.RSAKeyPair, *rsa.PrivateKey, *rsa.PublicKey](algo.KeySize2048) 1313 if err != nil { 1314 t.Fatalf("Failed to generate key pair: %v", err) 1315 } 1316 keyPair := manager.KeyPair() 1317 1318 // Create certificate 1319 certificate, err := cert.CreateSelfSignedCertificate(keyPair, cert.CertificateRequest{ 1320 Subject: pkix.Name{ 1321 CommonName: "Test Timestamp Signer", 1322 }, 1323 ValidFor: 24 * time.Hour, 1324 }) 1325 if err != nil { 1326 t.Fatalf("Failed to create certificate: %v", err) 1327 } 1328 1329 testData := []byte("Test data for timestamp verification") 1330 1331 // Create signature 1332 signature, err := SignDocument(testData, keyPair, certificate, SignOptions{ 1333 HashAlgorithm: crypto.SHA256, 1334 Format: FormatPKCS7, 1335 }) 1336 if err != nil { 1337 t.Fatalf("Failed to create signature: %v", err) 1338 } 1339 1340 // Test signature without timestamp 1341 err = VerifyTimestamp(signature, DefaultVerifyOptions()) 1342 if err == nil { 1343 t.Error("Timestamp verification should fail when signature has no timestamp") 1344 } 1345 1346 // Create timestamp authority certificate 1347 tsaManager, err := keypair.Generate[algo.KeySize, *algo.RSAKeyPair, *rsa.PrivateKey, *rsa.PublicKey](algo.KeySize2048) 1348 if err != nil { 1349 t.Fatalf("Failed to generate TSA key pair: %v", err) 1350 } 1351 tsaKeyPair := tsaManager.KeyPair() 1352 1353 tsaCert, err := cert.CreateSelfSignedCertificate(tsaKeyPair, cert.CertificateRequest{ 1354 Subject: pkix.Name{ 1355 CommonName: "Test TSA", 1356 }, 1357 ValidFor: 365 * 24 * time.Hour, 1358 }) 1359 if err != nil { 1360 t.Fatalf("Failed to create TSA certificate: %v", err) 1361 } 1362 1363 // Add timestamp to signature 1364 signature.Timestamp = &Timestamp{ 1365 Time: time.Now(), 1366 Certificate: tsaCert.Certificate, 1367 Token: []byte("mock_timestamp_token"), 1368 } 1369 1370 // Test successful timestamp verification 1371 err = VerifyTimestamp(signature, DefaultVerifyOptions()) 1372 if err != nil { 1373 t.Errorf("Timestamp verification should succeed: %v", err) 1374 } 1375 1376 // Test with expired timestamp certificate 1377 expiredTSACert, err := cert.CreateSelfSignedCertificate(tsaKeyPair, cert.CertificateRequest{ 1378 Subject: pkix.Name{ 1379 CommonName: "Expired TSA", 1380 }, 1381 ValidFor: -24 * time.Hour, // Already expired 1382 }) 1383 if err != nil { 1384 t.Fatalf("Failed to create expired TSA certificate: %v", err) 1385 } 1386 1387 signature.Timestamp.Certificate = expiredTSACert.Certificate 1388 1389 err = VerifyTimestamp(signature, DefaultVerifyOptions()) 1390 if err == nil { 1391 t.Error("Timestamp verification should fail with expired TSA certificate") 1392 } 1393 1394 // Test with empty timestamp token 1395 signature.Timestamp.Certificate = tsaCert.Certificate 1396 signature.Timestamp.Token = []byte{} 1397 1398 err = VerifyTimestamp(signature, DefaultVerifyOptions()) 1399 if err == nil { 1400 t.Error("Timestamp verification should fail with empty token") 1401 } 1402 1403 // Test with nil timestamp certificate 1404 signature.Timestamp.Certificate = nil 1405 signature.Timestamp.Token = []byte("mock_token") 1406 1407 err = VerifyTimestamp(signature, DefaultVerifyOptions()) 1408 if err != nil { 1409 t.Errorf("Timestamp verification should succeed with nil certificate: %v", err) 1410 } 1411 } 1412 1413 // TestExtractCertificateFromSignature tests the ExtractCertificateFromSignature function (0% coverage) 1414 func TestExtractCertificateFromSignature(t *testing.T) { 1415 // Generate key pair and certificate 1416 manager, err := keypair.Generate[algo.KeySize, *algo.RSAKeyPair, *rsa.PrivateKey, *rsa.PublicKey](algo.KeySize2048) 1417 if err != nil { 1418 t.Fatalf("Failed to generate key pair: %v", err) 1419 } 1420 keyPair := manager.KeyPair() 1421 1422 certificate, err := cert.CreateSelfSignedCertificate(keyPair, cert.CertificateRequest{ 1423 Subject: pkix.Name{ 1424 CommonName: "Test Certificate Extractor", 1425 }, 1426 ValidFor: 24 * time.Hour, 1427 }) 1428 if err != nil { 1429 t.Fatalf("Failed to create certificate: %v", err) 1430 } 1431 1432 testData := []byte("Test data for certificate extraction") 1433 1434 // Create signature 1435 signature, err := SignDocument(testData, keyPair, certificate, SignOptions{ 1436 HashAlgorithm: crypto.SHA256, 1437 Format: FormatPKCS7, 1438 IncludeCertificate: true, 1439 }) 1440 if err != nil { 1441 t.Fatalf("Failed to create signature: %v", err) 1442 } 1443 1444 // Test successful certificate extraction 1445 extractedCert, err := ExtractCertificateFromSignature(signature) 1446 if err != nil { 1447 t.Errorf("Certificate extraction should succeed: %v", err) 1448 } 1449 1450 if extractedCert == nil { 1451 t.Error("Extracted certificate should not be nil") 1452 } 1453 1454 if extractedCert.Subject.CommonName != "Test Certificate Extractor" { 1455 t.Errorf("Expected common name 'Test Certificate Extractor', got '%s'", extractedCert.Subject.CommonName) 1456 } 1457 1458 // Test with nil signature 1459 _, err = ExtractCertificateFromSignature(nil) 1460 if err == nil { 1461 t.Error("Certificate extraction should fail with nil signature") 1462 } 1463 1464 // Test with signature that has no certificate 1465 sigWithoutCert := &Signature{ 1466 Algorithm: signature.Algorithm, 1467 HashAlgorithm: signature.HashAlgorithm, 1468 Data: signature.Data, 1469 Certificate: nil, 1470 } 1471 1472 _, err = ExtractCertificateFromSignature(sigWithoutCert) 1473 if err == nil { 1474 t.Error("Certificate extraction should fail when signature has no certificate") 1475 } 1476 } 1477 1478 // TestExtractCertificateChainFromSignature tests the ExtractCertificateChainFromSignature function (0% coverage) 1479 func TestExtractCertificateChainFromSignature(t *testing.T) { 1480 // Generate key pairs for CA and end entity 1481 caManager, err := keypair.Generate[algo.KeySize, *algo.RSAKeyPair, *rsa.PrivateKey, *rsa.PublicKey](algo.KeySize2048) 1482 if err != nil { 1483 t.Fatalf("Failed to generate CA key pair: %v", err) 1484 } 1485 caKeyPair := caManager.KeyPair() 1486 1487 caCert, err := cert.CreateCACertificate(caKeyPair, cert.CertificateRequest{ 1488 Subject: pkix.Name{ 1489 CommonName: "Test CA for Chain", 1490 }, 1491 ValidFor: 365 * 24 * time.Hour, 1492 }) 1493 if err != nil { 1494 t.Fatalf("Failed to create CA certificate: %v", err) 1495 } 1496 1497 endEntityManager, err := keypair.Generate[algo.KeySize, *algo.RSAKeyPair, *rsa.PrivateKey, *rsa.PublicKey](algo.KeySize2048) 1498 if err != nil { 1499 t.Fatalf("Failed to generate end entity key pair: %v", err) 1500 } 1501 endEntityKeyPair := endEntityManager.KeyPair() 1502 1503 endEntityCert, err := cert.SignCertificate(caCert, caKeyPair, cert.CertificateRequest{ 1504 Subject: pkix.Name{ 1505 CommonName: "Test End Entity for Chain", 1506 }, 1507 ValidFor: 30 * 24 * time.Hour, 1508 }, endEntityKeyPair.PublicKey) 1509 if err != nil { 1510 t.Fatalf("Failed to create end entity certificate: %v", err) 1511 } 1512 1513 testData := []byte("Test data for certificate chain extraction") 1514 1515 // Create signature 1516 signature, err := SignDocument(testData, endEntityKeyPair, endEntityCert, SignOptions{ 1517 HashAlgorithm: crypto.SHA256, 1518 Format: FormatPKCS7, 1519 IncludeCertificate: true, 1520 }) 1521 if err != nil { 1522 t.Fatalf("Failed to create signature: %v", err) 1523 } 1524 1525 // Add certificate chain to signature 1526 signature.CertificateChain = []*x509.Certificate{caCert.Certificate} 1527 1528 // Test successful certificate chain extraction 1529 extractedChain, err := ExtractCertificateChainFromSignature(signature) 1530 if err != nil { 1531 t.Errorf("Certificate chain extraction should succeed: %v", err) 1532 } 1533 1534 if len(extractedChain) != 1 { 1535 t.Errorf("Expected 1 certificate in chain, got %d", len(extractedChain)) 1536 } 1537 1538 if extractedChain[0].Subject.CommonName != "Test CA for Chain" { 1539 t.Errorf("Expected CA common name 'Test CA for Chain', got '%s'", extractedChain[0].Subject.CommonName) 1540 } 1541 1542 // Test with nil signature 1543 _, err = ExtractCertificateChainFromSignature(nil) 1544 if err == nil { 1545 t.Error("Certificate chain extraction should fail with nil signature") 1546 } 1547 1548 // Test with signature that has no certificate chain 1549 sigWithoutChain := &Signature{ 1550 Algorithm: signature.Algorithm, 1551 HashAlgorithm: signature.HashAlgorithm, 1552 Data: signature.Data, 1553 Certificate: signature.Certificate, 1554 CertificateChain: nil, 1555 } 1556 1557 _, err = ExtractCertificateChainFromSignature(sigWithoutChain) 1558 if err == nil { 1559 t.Error("Certificate chain extraction should fail when signature has no certificate chain") 1560 } 1561 1562 // Test with empty certificate chain 1563 sigWithEmptyChain := &Signature{ 1564 Algorithm: signature.Algorithm, 1565 HashAlgorithm: signature.HashAlgorithm, 1566 Data: signature.Data, 1567 Certificate: signature.Certificate, 1568 CertificateChain: []*x509.Certificate{}, 1569 } 1570 1571 _, err = ExtractCertificateChainFromSignature(sigWithEmptyChain) 1572 if err == nil { 1573 t.Error("Certificate chain extraction should fail when signature has empty certificate chain") 1574 } 1575 }