github.com/jasoet/gopki@v1.15.0/pkcs12/pkcs12_simple_test.go (about)

     1  package pkcs12
     2  
     3  import (
     4  	"crypto/rand"
     5  	"crypto/rsa"
     6  	"crypto/x509"
     7  	"crypto/x509/pkix"
     8  	"math/big"
     9  	"os"
    10  	"path/filepath"
    11  	"testing"
    12  	"time"
    13  )
    14  
    15  func TestSimpleP12Operations(t *testing.T) {
    16  	tempDir := t.TempDir()
    17  
    18  	t.Run("Basic Create and Load", func(t *testing.T) {
    19  		// Generate RSA key pair
    20  		privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
    21  		if err != nil {
    22  			t.Fatalf("Failed to generate RSA keys: %v", err)
    23  		}
    24  
    25  		// Create self-signed 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(365 * 24 * time.Hour),
    34  			KeyUsage:     x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment,
    35  			SerialNumber: big.NewInt(1),
    36  		}
    37  
    38  		certDER, err := x509.CreateCertificate(rand.Reader, template, template, &privateKey.PublicKey, privateKey)
    39  		if err != nil {
    40  			t.Fatalf("Failed to create certificate: %v", err)
    41  		}
    42  
    43  		certificate, err := x509.ParseCertificate(certDER)
    44  		if err != nil {
    45  			t.Fatalf("Failed to parse certificate: %v", err)
    46  		}
    47  
    48  		// Create P12 file
    49  		p12File := filepath.Join(tempDir, "test.p12")
    50  		password := "test123"
    51  		opts := DefaultCreateOptions(password)
    52  
    53  		err = CreateP12File(p12File, privateKey, certificate, nil, opts)
    54  		if err != nil {
    55  			t.Fatalf("Failed to create P12 file: %v", err)
    56  		}
    57  
    58  		// Verify file was created
    59  		if _, err := os.Stat(p12File); os.IsNotExist(err) {
    60  			t.Fatalf("P12 file was not created")
    61  		}
    62  
    63  		// Load P12 file
    64  		loadOpts := DefaultLoadOptions(password)
    65  		container, err := LoadFromP12File(p12File, loadOpts)
    66  		if err != nil {
    67  			t.Fatalf("Failed to load P12 file: %v", err)
    68  		}
    69  
    70  		// Validate container
    71  		if err := container.Validate(); err != nil {
    72  			t.Errorf("Container validation failed: %v", err)
    73  		}
    74  
    75  		// Check key type
    76  		if container.GetKeyType() != "RSA" {
    77  			t.Errorf("Expected RSA key type, got %s", container.GetKeyType())
    78  		}
    79  
    80  		// Check certificate subject
    81  		if container.Certificate.Subject.CommonName != "Test Certificate" {
    82  			t.Errorf("Certificate subject mismatch")
    83  		}
    84  	})
    85  
    86  	t.Run("Generate Test P12", func(t *testing.T) {
    87  		p12File := filepath.Join(tempDir, "generated.p12")
    88  		password := "generated123"
    89  
    90  		err := GenerateTestP12(p12File, password)
    91  		if err != nil {
    92  			t.Fatalf("Failed to generate test P12: %v", err)
    93  		}
    94  
    95  		// Verify the generated file can be loaded
    96  		loadOpts := DefaultLoadOptions(password)
    97  		container, err := LoadFromP12File(p12File, loadOpts)
    98  		if err != nil {
    99  			t.Fatalf("Failed to load generated test P12: %v", err)
   100  		}
   101  
   102  		if container.Certificate.Subject.CommonName != "Test Certificate" {
   103  			t.Errorf("Generated test certificate has wrong subject")
   104  		}
   105  	})
   106  
   107  	t.Run("Quick Functions", func(t *testing.T) {
   108  		// Generate key and certificate
   109  		privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
   110  		if err != nil {
   111  			t.Fatalf("Failed to generate RSA keys: %v", err)
   112  		}
   113  
   114  		template := &x509.Certificate{
   115  			Subject: pkix.Name{
   116  				CommonName: "Quick Test",
   117  			},
   118  			NotBefore:    time.Now(),
   119  			NotAfter:     time.Now().Add(365 * 24 * time.Hour),
   120  			KeyUsage:     x509.KeyUsageDigitalSignature,
   121  			SerialNumber: big.NewInt(2),
   122  		}
   123  
   124  		certDER, err := x509.CreateCertificate(rand.Reader, template, template, &privateKey.PublicKey, privateKey)
   125  		if err != nil {
   126  			t.Fatalf("Failed to create certificate: %v", err)
   127  		}
   128  
   129  		certificate, err := x509.ParseCertificate(certDER)
   130  		if err != nil {
   131  			t.Fatalf("Failed to parse certificate: %v", err)
   132  		}
   133  
   134  		// Quick create
   135  		p12File := filepath.Join(tempDir, "quick.p12")
   136  		password := "quick123"
   137  
   138  		err = QuickCreateP12(p12File, password, privateKey, certificate)
   139  		if err != nil {
   140  			t.Fatalf("QuickCreateP12 failed: %v", err)
   141  		}
   142  
   143  		// Quick load
   144  		container, err := QuickLoadP12(p12File, password)
   145  		if err != nil {
   146  			t.Fatalf("QuickLoadP12 failed: %v", err)
   147  		}
   148  
   149  		if container.Certificate.Subject.CommonName != "Quick Test" {
   150  			t.Errorf("Quick load certificate subject mismatch")
   151  		}
   152  	})
   153  }
   154  
   155  func TestP12ErrorHandling(t *testing.T) {
   156  	tempDir := t.TempDir()
   157  
   158  	t.Run("Invalid Password", func(t *testing.T) {
   159  		// Create a P12 file first
   160  		err := GenerateTestP12(filepath.Join(tempDir, "test.p12"), "correct_password")
   161  		if err != nil {
   162  			t.Fatalf("Failed to generate test P12: %v", err)
   163  		}
   164  
   165  		// Try to load with wrong password
   166  		loadOpts := DefaultLoadOptions("wrong_password")
   167  		_, err = LoadFromP12File(filepath.Join(tempDir, "test.p12"), loadOpts)
   168  		if err == nil {
   169  			t.Error("Expected error with wrong password")
   170  		}
   171  	})
   172  
   173  	t.Run("Missing File", func(t *testing.T) {
   174  		loadOpts := DefaultLoadOptions("password")
   175  		_, err := LoadFromP12File("nonexistent.p12", loadOpts)
   176  		if err == nil {
   177  			t.Error("Expected error for missing file")
   178  		}
   179  	})
   180  
   181  	t.Run("Nil Parameters", func(t *testing.T) {
   182  		opts := DefaultCreateOptions("password")
   183  
   184  		// Test nil private key
   185  		_, err := CreateP12[*rsa.PrivateKey](nil, &x509.Certificate{}, nil, opts)
   186  		if err == nil {
   187  			t.Error("Expected error for nil private key")
   188  		}
   189  
   190  		// Test nil certificate
   191  		privateKey, _ := rsa.GenerateKey(rand.Reader, 2048)
   192  		_, err = CreateP12(privateKey, nil, nil, opts)
   193  		if err == nil {
   194  			t.Error("Expected error for nil certificate")
   195  		}
   196  	})
   197  }
   198  
   199  func TestP12CertificateInfo(t *testing.T) {
   200  	tempDir := t.TempDir()
   201  
   202  	// Create test P12
   203  	p12File := filepath.Join(tempDir, "info_test.p12")
   204  	err := GenerateTestP12(p12File, "test123")
   205  	if err != nil {
   206  		t.Fatalf("Failed to generate test P12: %v", err)
   207  	}
   208  
   209  	// Load and get info
   210  	container, err := QuickLoadP12(p12File, "test123")
   211  	if err != nil {
   212  		t.Fatalf("Failed to load P12: %v", err)
   213  	}
   214  
   215  	info := GetCertificateInfo(container.Certificate)
   216  	if info == nil {
   217  		t.Fatal("Certificate info is nil")
   218  	}
   219  
   220  	// Check some expected fields
   221  	if subject, ok := info["subject"].(string); !ok || subject == "" {
   222  		t.Error("Subject field missing or empty")
   223  	}
   224  
   225  	if keyUsage, ok := info["key_usage"].([]string); !ok || len(keyUsage) == 0 {
   226  		t.Error("Key usage field missing or empty")
   227  	}
   228  }