github.com/jasoet/gopki@v1.15.0/encryption/asymmetric/ecdsa_test.go (about)

     1  package asymmetric
     2  
     3  import (
     4  	"fmt"
     5  	"strings"
     6  	"testing"
     7  
     8  	"github.com/jasoet/gopki/encryption"
     9  	"github.com/jasoet/gopki/keypair/algo"
    10  )
    11  
    12  func TestEncryptWithECDSA(t *testing.T) {
    13  	testCases := []struct {
    14  		name  string
    15  		curve algo.ECDSACurve
    16  	}{
    17  		{"P256", algo.P256},
    18  		{"P384", algo.P384},
    19  		{"P521", algo.P521},
    20  	}
    21  
    22  	opts := encryption.DefaultEncryptOptions()
    23  
    24  	for _, tc := range testCases {
    25  		t.Run(tc.name, func(t *testing.T) {
    26  			ecdsaKeys, err := algo.GenerateECDSAKeyPair(tc.curve)
    27  			if err != nil {
    28  				t.Fatalf("Failed to generate ECDSA key pair for %s: %v", tc.name, err)
    29  			}
    30  
    31  			data := []byte("test data for ECDSA encryption")
    32  
    33  			encrypted, err := EncryptWithECDSA(data, ecdsaKeys, opts)
    34  			if err != nil {
    35  				t.Fatalf("Failed to encrypt with ECDSA %s: %v", tc.name, err)
    36  			}
    37  
    38  			if encrypted == nil {
    39  				t.Fatal("Encrypted data is nil")
    40  			}
    41  			if encrypted.Algorithm != encryption.AlgorithmECDH {
    42  				t.Errorf("Expected algorithm %s, got %s", encryption.AlgorithmECDH, encrypted.Algorithm)
    43  			}
    44  			if len(encrypted.Data) == 0 {
    45  				t.Error("Encrypted data is empty")
    46  			}
    47  			if len(encrypted.EncryptedKey) == 0 {
    48  				t.Error("Ephemeral public key should be stored in EncryptedKey")
    49  			}
    50  			if len(encrypted.IV) == 0 {
    51  				t.Error("IV should be present")
    52  			}
    53  			if len(encrypted.Tag) == 0 {
    54  				t.Error("Authentication tag should be present")
    55  			}
    56  			if encrypted.Timestamp.IsZero() {
    57  				t.Error("Timestamp should be set")
    58  			}
    59  		})
    60  	}
    61  }
    62  
    63  func TestEncryptWithECDSALargeData(t *testing.T) {
    64  	ecdsaKeys, err := algo.GenerateECDSAKeyPair(algo.P256)
    65  	if err != nil {
    66  		t.Fatalf("Failed to generate ECDSA key pair: %v", err)
    67  	}
    68  
    69  	opts := encryption.DefaultEncryptOptions()
    70  
    71  	// Test with various data sizes
    72  	testSizes := []int{0, 1, 100, 1024, 10240, 100000}
    73  
    74  	for _, size := range testSizes {
    75  		t.Run(fmt.Sprintf("Size%d", size), func(t *testing.T) {
    76  			data := make([]byte, size)
    77  			for i := range data {
    78  				data[i] = byte(i % 256)
    79  			}
    80  
    81  			encrypted, err := EncryptWithECDSA(data, ecdsaKeys, opts)
    82  			if err != nil {
    83  				t.Fatalf("Failed to encrypt %d bytes: %v", size, err)
    84  			}
    85  
    86  			if encrypted == nil {
    87  				t.Fatal("Encrypted data is nil")
    88  			}
    89  
    90  			// ECDSA with AES-GCM can handle any size data
    91  			if len(encrypted.Data) == 0 && size > 0 {
    92  				t.Error("Encrypted data should not be empty for non-empty input")
    93  			}
    94  		})
    95  	}
    96  }
    97  
    98  func TestDecryptWithECDSA(t *testing.T) {
    99  	testCases := []struct {
   100  		name  string
   101  		curve algo.ECDSACurve
   102  	}{
   103  		{"P256", algo.P256},
   104  		{"P384", algo.P384},
   105  		{"P521", algo.P521},
   106  	}
   107  
   108  	opts := encryption.DefaultEncryptOptions()
   109  	decryptOpts := encryption.DefaultDecryptOptions()
   110  
   111  	for _, tc := range testCases {
   112  		t.Run(tc.name, func(t *testing.T) {
   113  			ecdsaKeys, err := algo.GenerateECDSAKeyPair(tc.curve)
   114  			if err != nil {
   115  				t.Fatalf("Failed to generate ECDSA key pair for %s: %v", tc.name, err)
   116  			}
   117  
   118  			data := []byte("test data for ECDSA decryption")
   119  
   120  			encrypted, err := EncryptWithECDSA(data, ecdsaKeys, opts)
   121  			if err != nil {
   122  				t.Fatalf("Failed to encrypt: %v", err)
   123  			}
   124  
   125  			decrypted, err := DecryptWithECDSA(encrypted, ecdsaKeys, decryptOpts)
   126  			if err != nil {
   127  				t.Fatalf("Failed to decrypt: %v", err)
   128  			}
   129  
   130  			if string(decrypted) != string(data) {
   131  				t.Errorf("Decrypted data doesn't match. Expected: %s, Got: %s", string(data), string(decrypted))
   132  			}
   133  		})
   134  	}
   135  }
   136  
   137  func TestDecryptWithECDSAErrorCases(t *testing.T) {
   138  	ecdsaKeys, err := algo.GenerateECDSAKeyPair(algo.P256)
   139  	if err != nil {
   140  		t.Fatalf("Failed to generate ECDSA key pair: %v", err)
   141  	}
   142  
   143  	opts := encryption.DefaultEncryptOptions()
   144  	decryptOpts := encryption.DefaultDecryptOptions()
   145  	data := []byte("test data")
   146  
   147  	t.Run("WrongAlgorithm", func(t *testing.T) {
   148  		encrypted := &encryption.EncryptedData{
   149  			Algorithm: encryption.AlgorithmRSAOAEP, // Wrong algorithm
   150  			Data:      []byte("encrypted"),
   151  		}
   152  
   153  		_, err := DecryptWithECDSA(encrypted, ecdsaKeys, decryptOpts)
   154  		if err == nil {
   155  			t.Error("Expected error for wrong algorithm")
   156  		}
   157  		if !strings.Contains(err.Error(), "expected ECDH") {
   158  			t.Errorf("Expected algorithm error, got: %v", err)
   159  		}
   160  	})
   161  
   162  	t.Run("InvalidEphemeralKey", func(t *testing.T) {
   163  		encrypted, err := EncryptWithECDSA(data, ecdsaKeys, opts)
   164  		if err != nil {
   165  			t.Fatalf("Failed to encrypt: %v", err)
   166  		}
   167  
   168  		// Corrupt the ephemeral key
   169  		encrypted.EncryptedKey = []byte("invalid ephemeral key")
   170  
   171  		_, err = DecryptWithECDSA(encrypted, ecdsaKeys, decryptOpts)
   172  		if err == nil {
   173  			t.Error("Expected error for invalid ephemeral key")
   174  		}
   175  	})
   176  
   177  	t.Run("CorruptedData", func(t *testing.T) {
   178  		encrypted, err := EncryptWithECDSA(data, ecdsaKeys, opts)
   179  		if err != nil {
   180  			t.Fatalf("Failed to encrypt: %v", err)
   181  		}
   182  
   183  		// Corrupt the encrypted data
   184  		encrypted.Data[0] ^= 0xFF
   185  
   186  		_, err = DecryptWithECDSA(encrypted, ecdsaKeys, decryptOpts)
   187  		if err == nil {
   188  			t.Error("Expected error for corrupted data")
   189  		}
   190  	})
   191  
   192  	t.Run("CorruptedTag", func(t *testing.T) {
   193  		encrypted, err := EncryptWithECDSA(data, ecdsaKeys, opts)
   194  		if err != nil {
   195  			t.Fatalf("Failed to encrypt: %v", err)
   196  		}
   197  
   198  		// Corrupt the authentication tag
   199  		encrypted.Tag[0] ^= 0xFF
   200  
   201  		_, err = DecryptWithECDSA(encrypted, ecdsaKeys, decryptOpts)
   202  		if err == nil {
   203  			t.Error("Expected error for corrupted authentication tag")
   204  		}
   205  	})
   206  
   207  	t.Run("WrongKeyPair", func(t *testing.T) {
   208  		// Generate different key pair
   209  		wrongKeys, err := algo.GenerateECDSAKeyPair(algo.P256)
   210  		if err != nil {
   211  			t.Fatalf("Failed to generate wrong ECDSA key pair: %v", err)
   212  		}
   213  
   214  		encrypted, err := EncryptWithECDSA(data, ecdsaKeys, opts)
   215  		if err != nil {
   216  			t.Fatalf("Failed to encrypt: %v", err)
   217  		}
   218  
   219  		_, err = DecryptWithECDSA(encrypted, wrongKeys, decryptOpts)
   220  		if err == nil {
   221  			t.Error("Expected error for wrong key pair")
   222  		}
   223  	})
   224  
   225  	t.Run("InvalidDecryptOptions", func(t *testing.T) {
   226  		encrypted, err := EncryptWithECDSA(data, ecdsaKeys, opts)
   227  		if err != nil {
   228  			t.Fatalf("Failed to encrypt: %v", err)
   229  		}
   230  
   231  		invalidDecryptOpts := encryption.DecryptOptions{
   232  			MaxAge: -1, // Invalid negative max age
   233  		}
   234  
   235  		_, err = DecryptWithECDSA(encrypted, ecdsaKeys, invalidDecryptOpts)
   236  		if err == nil {
   237  			t.Error("Expected error for invalid decrypt options")
   238  		}
   239  	})
   240  }
   241  
   242  func TestECDSARoundTrip(t *testing.T) {
   243  	curves := []struct {
   244  		name  string
   245  		curve algo.ECDSACurve
   246  	}{
   247  		{"P256", algo.P256},
   248  		{"P384", algo.P384},
   249  		{"P521", algo.P521},
   250  	}
   251  
   252  	dataSizes := []int{0, 1, 16, 100, 1024, 10000}
   253  	opts := encryption.DefaultEncryptOptions()
   254  	decryptOpts := encryption.DefaultDecryptOptions()
   255  
   256  	for _, c := range curves {
   257  		for _, size := range dataSizes {
   258  			t.Run(fmt.Sprintf("%s_Size%d", c.name, size), func(t *testing.T) {
   259  				ecdsaKeys, err := algo.GenerateECDSAKeyPair(c.curve)
   260  				if err != nil {
   261  					t.Fatalf("Failed to generate ECDSA key pair: %v", err)
   262  				}
   263  
   264  				data := make([]byte, size)
   265  				for i := range data {
   266  					data[i] = byte(i % 256)
   267  				}
   268  
   269  				encrypted, err := EncryptWithECDSA(data, ecdsaKeys, opts)
   270  				if err != nil {
   271  					t.Fatalf("Failed to encrypt: %v", err)
   272  				}
   273  
   274  				decrypted, err := DecryptWithECDSA(encrypted, ecdsaKeys, decryptOpts)
   275  				if err != nil {
   276  					t.Fatalf("Failed to decrypt: %v", err)
   277  				}
   278  
   279  				if len(decrypted) != len(data) {
   280  					t.Errorf("Length mismatch. Expected: %d, Got: %d", len(data), len(decrypted))
   281  				}
   282  
   283  				for i := range data {
   284  					if decrypted[i] != data[i] {
   285  						t.Errorf("Data mismatch at position %d. Expected: %d, Got: %d", i, data[i], decrypted[i])
   286  						break
   287  					}
   288  				}
   289  			})
   290  		}
   291  	}
   292  }
   293  
   294  func TestECDSAWithMetadata(t *testing.T) {
   295  	ecdsaKeys, err := algo.GenerateECDSAKeyPair(algo.P256)
   296  	if err != nil {
   297  		t.Fatalf("Failed to generate ECDSA key pair: %v", err)
   298  	}
   299  
   300  	data := []byte("test data with metadata")
   301  	opts := encryption.EncryptOptions{
   302  		Algorithm: encryption.AlgorithmECDH,
   303  		Format:    encryption.FormatCMS,
   304  		Metadata: map[string]interface{}{
   305  			"curve":      "P256",
   306  			"test_value": 123,
   307  			"nested": map[string]interface{}{
   308  				"inner": "value",
   309  			},
   310  		},
   311  	}
   312  
   313  	encrypted, err := EncryptWithECDSA(data, ecdsaKeys, opts)
   314  	if err != nil {
   315  		t.Fatalf("Failed to encrypt: %v", err)
   316  	}
   317  
   318  	if encrypted.Metadata == nil {
   319  		t.Error("Metadata should be preserved")
   320  	}
   321  
   322  	if val, ok := encrypted.Metadata["curve"]; !ok || val != "P256" {
   323  		t.Error("String metadata not preserved correctly")
   324  	}
   325  
   326  	if val, ok := encrypted.Metadata["test_value"]; !ok || val != 123 {
   327  		t.Error("Numeric metadata not preserved correctly")
   328  	}
   329  
   330  	if nested, ok := encrypted.Metadata["nested"].(map[string]interface{}); !ok {
   331  		t.Error("Nested metadata not preserved correctly")
   332  	} else {
   333  		if inner, ok := nested["inner"]; !ok || inner != "value" {
   334  			t.Error("Nested inner value not preserved correctly")
   335  		}
   336  	}
   337  }
   338  
   339  func TestECDSAKeyConversion(t *testing.T) {
   340  	// Test that ECDSA keys can be properly converted to ECDH
   341  	// P224 is not supported by crypto/ecdh
   342  	curves := []algo.ECDSACurve{algo.P256, algo.P384, algo.P521}
   343  
   344  	for _, curve := range curves {
   345  		t.Run(fmt.Sprintf("Curve%v", curve), func(t *testing.T) {
   346  			ecdsaKeys, err := algo.GenerateECDSAKeyPair(curve)
   347  			if err != nil {
   348  				t.Fatalf("Failed to generate ECDSA key pair: %v", err)
   349  			}
   350  
   351  			// Test that the key conversion works in encryption
   352  			data := []byte("test key conversion")
   353  			opts := encryption.DefaultEncryptOptions()
   354  
   355  			encrypted, err := EncryptWithECDSA(data, ecdsaKeys, opts)
   356  			if err != nil {
   357  				t.Fatalf("Failed to encrypt (key conversion failed): %v", err)
   358  			}
   359  
   360  			// Verify ephemeral key is present and valid
   361  			if len(encrypted.EncryptedKey) == 0 {
   362  				t.Error("Ephemeral key should be present")
   363  			}
   364  
   365  			// Test decryption (which also requires key conversion)
   366  			decrypted, err := DecryptWithECDSA(encrypted, ecdsaKeys, encryption.DefaultDecryptOptions())
   367  			if err != nil {
   368  				t.Fatalf("Failed to decrypt (key conversion failed): %v", err)
   369  			}
   370  
   371  			if string(decrypted) != string(data) {
   372  				t.Error("Round-trip failed due to key conversion issues")
   373  			}
   374  		})
   375  	}
   376  }
   377  
   378  func TestECDSAP224NotSupported(t *testing.T) {
   379  	// Test that P224 curve is not supported due to crypto/ecdh limitations
   380  	ecdsaKeys, err := algo.GenerateECDSAKeyPair(algo.P224)
   381  	if err != nil {
   382  		t.Fatalf("Failed to generate ECDSA P224 key pair: %v", err)
   383  	}
   384  
   385  	data := []byte("test data")
   386  	opts := encryption.DefaultEncryptOptions()
   387  
   388  	_, err = EncryptWithECDSA(data, ecdsaKeys, opts)
   389  	if err == nil {
   390  		t.Error("Expected error for P224 curve (not supported by crypto/ecdh)")
   391  	}
   392  	if !strings.Contains(err.Error(), "unsupported curve") {
   393  		t.Errorf("Expected unsupported curve error, got: %v", err)
   394  	}
   395  }
   396  
   397  func TestECDSAInvalidOptions(t *testing.T) {
   398  	ecdsaKeys, err := algo.GenerateECDSAKeyPair(algo.P256)
   399  	if err != nil {
   400  		t.Fatalf("Failed to generate ECDSA key pair: %v", err)
   401  	}
   402  
   403  	data := []byte("test data")
   404  
   405  	t.Run("InvalidEncryptOptions", func(t *testing.T) {
   406  		invalidOpts := encryption.EncryptOptions{
   407  			Algorithm: "invalid_algorithm",
   408  			Format:    encryption.FormatCMS,
   409  		}
   410  
   411  		_, err := EncryptWithECDSA(data, ecdsaKeys, invalidOpts)
   412  		if err == nil {
   413  			t.Error("Expected error for invalid encrypt options")
   414  		}
   415  	})
   416  }