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

     1  package asymmetric
     2  
     3  import (
     4  	"crypto/ed25519"
     5  	"crypto/rand"
     6  	"crypto/rsa"
     7  	"fmt"
     8  	"strings"
     9  	"testing"
    10  
    11  	"github.com/jasoet/gopki/encryption"
    12  	"github.com/jasoet/gopki/keypair/algo"
    13  )
    14  
    15  func TestEncrypt(t *testing.T) {
    16  	data := []byte("test data for encryption")
    17  	opts := encryption.DefaultEncryptOptions()
    18  
    19  	t.Run("RSA", func(t *testing.T) {
    20  		rsaKeys, err := algo.GenerateRSAKeyPair(algo.KeySize2048)
    21  		if err != nil {
    22  			t.Fatalf("Failed to generate RSA key pair: %v", err)
    23  		}
    24  
    25  		encrypted, err := Encrypt(data, rsaKeys, opts)
    26  		if err != nil {
    27  			t.Fatalf("Failed to encrypt with RSA: %v", err)
    28  		}
    29  
    30  		if encrypted == nil {
    31  			t.Fatal("Encrypted data is nil")
    32  		}
    33  		if encrypted.Algorithm != encryption.AlgorithmRSAOAEP {
    34  			t.Errorf("Expected algorithm %s, got %s", encryption.AlgorithmRSAOAEP, encrypted.Algorithm)
    35  		}
    36  		if len(encrypted.Data) == 0 {
    37  			t.Error("Encrypted data is empty")
    38  		}
    39  	})
    40  
    41  	t.Run("ECDSA", func(t *testing.T) {
    42  		ecdsaKeys, err := algo.GenerateECDSAKeyPair(algo.P256)
    43  		if err != nil {
    44  			t.Fatalf("Failed to generate ECDSA key pair: %v", err)
    45  		}
    46  
    47  		encrypted, err := Encrypt(data, ecdsaKeys, opts)
    48  		if err != nil {
    49  			t.Fatalf("Failed to encrypt with ECDSA: %v", err)
    50  		}
    51  
    52  		if encrypted == nil {
    53  			t.Fatal("Encrypted data is nil")
    54  		}
    55  		if encrypted.Algorithm != encryption.AlgorithmECDH {
    56  			t.Errorf("Expected algorithm %s, got %s", encryption.AlgorithmECDH, encrypted.Algorithm)
    57  		}
    58  		if len(encrypted.Data) == 0 {
    59  			t.Error("Encrypted data is empty")
    60  		}
    61  	})
    62  
    63  	t.Run("Ed25519", func(t *testing.T) {
    64  		ed25519Keys, err := algo.GenerateEd25519KeyPair()
    65  		if err != nil {
    66  			t.Fatalf("Failed to generate Ed25519 key pair: %v", err)
    67  		}
    68  
    69  		encrypted, err := Encrypt(data, ed25519Keys, opts)
    70  		if err != nil {
    71  			t.Fatalf("Failed to encrypt with Ed25519: %v", err)
    72  		}
    73  
    74  		if encrypted == nil {
    75  			t.Fatal("Encrypted data is nil")
    76  		}
    77  		if encrypted.Algorithm != encryption.AlgorithmX25519 {
    78  			t.Errorf("Expected algorithm %s, got %s", encryption.AlgorithmX25519, encrypted.Algorithm)
    79  		}
    80  		if len(encrypted.Data) == 0 {
    81  			t.Error("Encrypted data is empty")
    82  		}
    83  	})
    84  
    85  	t.Run("NilKeyType", func(t *testing.T) {
    86  		// Test with nil (which will cause a panic that we should handle gracefully)
    87  		defer func() {
    88  			if r := recover(); r != nil {
    89  				// This is expected - nil pointer dereference should be caught
    90  				t.Logf("Caught expected panic for nil key: %v", r)
    91  			}
    92  		}()
    93  
    94  		var nilKey *algo.RSAKeyPair
    95  		_, err := Encrypt(data, nilKey, opts)
    96  		if err == nil {
    97  			t.Error("Expected error for nil key type")
    98  		}
    99  	})
   100  }
   101  
   102  func TestDecrypt(t *testing.T) {
   103  	data := []byte("test data for decryption")
   104  	opts := encryption.DefaultEncryptOptions()
   105  	decryptOpts := encryption.DefaultDecryptOptions()
   106  
   107  	t.Run("RSA", func(t *testing.T) {
   108  		rsaKeys, err := algo.GenerateRSAKeyPair(algo.KeySize2048)
   109  		if err != nil {
   110  			t.Fatalf("Failed to generate RSA key pair: %v", err)
   111  		}
   112  
   113  		encrypted, err := Encrypt(data, rsaKeys, opts)
   114  		if err != nil {
   115  			t.Fatalf("Failed to encrypt: %v", err)
   116  		}
   117  
   118  		decrypted, err := Decrypt(encrypted, rsaKeys, decryptOpts)
   119  		if err != nil {
   120  			t.Fatalf("Failed to decrypt: %v", err)
   121  		}
   122  
   123  		if string(decrypted) != string(data) {
   124  			t.Errorf("Decrypted data doesn't match. Expected: %s, Got: %s", string(data), string(decrypted))
   125  		}
   126  	})
   127  
   128  	t.Run("ECDSA", func(t *testing.T) {
   129  		ecdsaKeys, err := algo.GenerateECDSAKeyPair(algo.P256)
   130  		if err != nil {
   131  			t.Fatalf("Failed to generate ECDSA key pair: %v", err)
   132  		}
   133  
   134  		encrypted, err := Encrypt(data, ecdsaKeys, opts)
   135  		if err != nil {
   136  			t.Fatalf("Failed to encrypt: %v", err)
   137  		}
   138  
   139  		decrypted, err := Decrypt(encrypted, ecdsaKeys, decryptOpts)
   140  		if err != nil {
   141  			t.Fatalf("Failed to decrypt: %v", err)
   142  		}
   143  
   144  		if string(decrypted) != string(data) {
   145  			t.Errorf("Decrypted data doesn't match. Expected: %s, Got: %s", string(data), string(decrypted))
   146  		}
   147  	})
   148  
   149  	t.Run("Ed25519", func(t *testing.T) {
   150  		ed25519Keys, err := algo.GenerateEd25519KeyPair()
   151  		if err != nil {
   152  			t.Fatalf("Failed to generate Ed25519 key pair: %v", err)
   153  		}
   154  
   155  		encrypted, err := Encrypt(data, ed25519Keys, opts)
   156  		if err != nil {
   157  			t.Fatalf("Failed to encrypt: %v", err)
   158  		}
   159  
   160  		decrypted, err := Decrypt(encrypted, ed25519Keys, decryptOpts)
   161  		if err != nil {
   162  			t.Fatalf("Failed to decrypt: %v", err)
   163  		}
   164  
   165  		if string(decrypted) != string(data) {
   166  			t.Errorf("Decrypted data doesn't match. Expected: %s, Got: %s", string(data), string(decrypted))
   167  		}
   168  	})
   169  
   170  	t.Run("NilKeyType", func(t *testing.T) {
   171  		// Test that nil keys are handled gracefully
   172  		defer func() {
   173  			if r := recover(); r != nil {
   174  				// This is expected - nil pointer dereference should be caught
   175  				t.Logf("Caught expected panic for nil key: %v", r)
   176  			}
   177  		}()
   178  
   179  		encrypted := &encryption.EncryptedData{
   180  			Algorithm: encryption.AlgorithmRSAOAEP,
   181  			Data:      []byte("test"),
   182  		}
   183  
   184  		var nilKey *algo.RSAKeyPair
   185  		_, err := Decrypt(encrypted, nilKey, decryptOpts)
   186  		if err == nil {
   187  			t.Error("Expected error for nil key type")
   188  		}
   189  	})
   190  }
   191  
   192  func TestEncryptForPublicKey(t *testing.T) {
   193  	data := []byte("test data for public key encryption")
   194  	opts := encryption.DefaultEncryptOptions()
   195  
   196  	t.Run("RSA", func(t *testing.T) {
   197  		rsaKeys, err := algo.GenerateRSAKeyPair(algo.KeySize2048)
   198  		if err != nil {
   199  			t.Fatalf("Failed to generate RSA key pair: %v", err)
   200  		}
   201  
   202  		encrypted, err := EncryptForPublicKey(data, rsaKeys.PublicKey, opts)
   203  		if err != nil {
   204  			t.Fatalf("Failed to encrypt for RSA public key: %v", err)
   205  		}
   206  
   207  		if encrypted == nil {
   208  			t.Fatal("Encrypted data is nil")
   209  		}
   210  		if encrypted.Algorithm != encryption.AlgorithmRSAOAEP {
   211  			t.Errorf("Expected algorithm %s, got %s", encryption.AlgorithmRSAOAEP, encrypted.Algorithm)
   212  		}
   213  	})
   214  
   215  	t.Run("ECDSA", func(t *testing.T) {
   216  		ecdsaKeys, err := algo.GenerateECDSAKeyPair(algo.P256)
   217  		if err != nil {
   218  			t.Fatalf("Failed to generate ECDSA key pair: %v", err)
   219  		}
   220  
   221  		encrypted, err := EncryptForPublicKey(data, ecdsaKeys.PublicKey, opts)
   222  		if err != nil {
   223  			t.Fatalf("ECDSA public key encryption failed: %v", err)
   224  		}
   225  		if encrypted.Algorithm != encryption.AlgorithmECDH {
   226  			t.Errorf("Expected ECDH algorithm, got %s", encrypted.Algorithm)
   227  		}
   228  	})
   229  
   230  	t.Run("Ed25519", func(t *testing.T) {
   231  		ed25519Keys, err := algo.GenerateEd25519KeyPair()
   232  		if err != nil {
   233  			t.Fatalf("Failed to generate Ed25519 key pair: %v", err)
   234  		}
   235  
   236  		// Ed25519 public-key-only encryption has partial implementation (may fail with certain keys)
   237  		_, err = EncryptForPublicKey(data, ed25519Keys.PublicKey, opts)
   238  		if err == nil {
   239  			t.Log("Ed25519 public-key-only encryption succeeded (key format compatible)")
   240  		} else {
   241  			// This is expected with current implementation
   242  			if !strings.Contains(err.Error(), "Ed25519 public-key-only encryption failed") {
   243  				t.Errorf("Expected Ed25519 conversion error, got: %v", err)
   244  			}
   245  			t.Logf("Ed25519 public-key-only encryption failed as expected: %v", err)
   246  		}
   247  	})
   248  
   249  	t.Run("NilPublicKey", func(t *testing.T) {
   250  		defer func() {
   251  			if r := recover(); r != nil {
   252  				// This is expected - nil pointer dereference should be caught
   253  				t.Logf("Caught expected panic for nil public key: %v", r)
   254  			}
   255  		}()
   256  
   257  		var nilKey *rsa.PublicKey
   258  		_, err := EncryptForPublicKey(data, nilKey, opts)
   259  		if err == nil {
   260  			t.Error("Expected error for nil public key")
   261  		}
   262  	})
   263  }
   264  
   265  func TestEncryptForPublicKeyAny(t *testing.T) {
   266  	data := []byte("test data for public key any encryption")
   267  	opts := encryption.DefaultEncryptOptions()
   268  
   269  	t.Run("RSA", func(t *testing.T) {
   270  		rsaPrivateKey, err := rsa.GenerateKey(rand.Reader, 2048)
   271  		if err != nil {
   272  			t.Fatalf("Failed to generate RSA key: %v", err)
   273  		}
   274  
   275  		encrypted, err := EncryptForPublicKeyAny(data, &rsaPrivateKey.PublicKey, opts)
   276  		if err != nil {
   277  			t.Fatalf("Failed to encrypt for RSA public key: %v", err)
   278  		}
   279  
   280  		if encrypted == nil {
   281  			t.Fatal("Encrypted data is nil")
   282  		}
   283  		if encrypted.Algorithm != encryption.AlgorithmRSAOAEP {
   284  			t.Errorf("Expected algorithm %s, got %s", encryption.AlgorithmRSAOAEP, encrypted.Algorithm)
   285  		}
   286  	})
   287  
   288  	t.Run("ECDSA", func(t *testing.T) {
   289  		ecdsaKeys, err := algo.GenerateECDSAKeyPair(algo.P256)
   290  		if err != nil {
   291  			t.Fatalf("Failed to generate ECDSA key pair: %v", err)
   292  		}
   293  
   294  		encrypted, err := EncryptForPublicKeyAny(data, ecdsaKeys.PublicKey, opts)
   295  		if err != nil {
   296  			t.Fatalf("ECDSA public key encryption failed: %v", err)
   297  		}
   298  		if encrypted.Algorithm != encryption.AlgorithmECDH {
   299  			t.Errorf("Expected ECDH algorithm, got %s", encrypted.Algorithm)
   300  		}
   301  	})
   302  
   303  	t.Run("Ed25519", func(t *testing.T) {
   304  		publicKey, _, err := ed25519.GenerateKey(rand.Reader)
   305  		if err != nil {
   306  			t.Fatalf("Failed to generate Ed25519 key: %v", err)
   307  		}
   308  
   309  		// Ed25519 public-key-only encryption has partial implementation (may fail with certain keys)
   310  		_, err = EncryptForPublicKeyAny(data, publicKey, opts)
   311  		if err == nil {
   312  			t.Log("Ed25519 public-key-only encryption succeeded (key format compatible)")
   313  		} else {
   314  			// This is expected with current implementation
   315  			if !strings.Contains(err.Error(), "Ed25519 public-key-only encryption failed") {
   316  				t.Errorf("Expected Ed25519 conversion error, got: %v", err)
   317  			}
   318  			t.Logf("Ed25519 public-key-only encryption failed as expected: %v", err)
   319  		}
   320  	})
   321  
   322  	t.Run("UnsupportedPublicKeyType", func(t *testing.T) {
   323  		type unsupportedPublicKey struct{}
   324  
   325  		_, err := EncryptForPublicKeyAny(data, &unsupportedPublicKey{}, opts)
   326  		if err == nil {
   327  			t.Error("Expected error for unsupported public key type")
   328  		}
   329  	})
   330  }
   331  
   332  func TestDecryptWithPrivateKey(t *testing.T) {
   333  	encrypted := &encryption.EncryptedData{
   334  		Algorithm: encryption.AlgorithmRSAOAEP,
   335  		Data:      []byte("test"),
   336  	}
   337  
   338  	rsaKeys, err := algo.GenerateRSAKeyPair(algo.KeySize2048)
   339  	if err != nil {
   340  		t.Fatalf("Failed to generate RSA key pair: %v", err)
   341  	}
   342  
   343  	_, err = DecryptWithPrivateKey(encrypted, rsaKeys.PrivateKey, encryption.DefaultDecryptOptions())
   344  	if err == nil {
   345  		t.Error("Expected error - DecryptWithPrivateKey should not be supported for asymmetric encryption")
   346  	}
   347  }
   348  
   349  func TestSupportedAlgorithms(t *testing.T) {
   350  	algorithms := SupportedAlgorithms()
   351  
   352  	expectedAlgorithms := []encryption.Algorithm{
   353  		encryption.AlgorithmRSAOAEP,
   354  		encryption.AlgorithmECDH,
   355  		encryption.AlgorithmX25519,
   356  	}
   357  
   358  	if len(algorithms) != len(expectedAlgorithms) {
   359  		t.Errorf("Expected %d algorithms, got %d", len(expectedAlgorithms), len(algorithms))
   360  	}
   361  
   362  	for _, expected := range expectedAlgorithms {
   363  		found := false
   364  		for _, alg := range algorithms {
   365  			if alg == expected {
   366  				found = true
   367  				break
   368  			}
   369  		}
   370  		if !found {
   371  			t.Errorf("Expected algorithm %s not found in supported algorithms", expected)
   372  		}
   373  	}
   374  }
   375  
   376  func TestRoundTripEncryption(t *testing.T) {
   377  	testData := [][]byte{
   378  		[]byte("short"),
   379  		[]byte("medium length test data for encryption"),
   380  		[]byte(""),
   381  	}
   382  
   383  	opts := encryption.DefaultEncryptOptions()
   384  	decryptOpts := encryption.DefaultDecryptOptions()
   385  
   386  	for _, data := range testData {
   387  		t.Run("RSA", func(t *testing.T) {
   388  			rsaKeys, err := algo.GenerateRSAKeyPair(algo.KeySize2048)
   389  			if err != nil {
   390  				t.Fatalf("Failed to generate RSA key pair: %v", err)
   391  			}
   392  
   393  			encrypted, err := Encrypt(data, rsaKeys, opts)
   394  			if err != nil {
   395  				t.Fatalf("Failed to encrypt: %v", err)
   396  			}
   397  
   398  			decrypted, err := Decrypt(encrypted, rsaKeys, decryptOpts)
   399  			if err != nil {
   400  				t.Fatalf("Failed to decrypt: %v", err)
   401  			}
   402  
   403  			if string(decrypted) != string(data) {
   404  				t.Errorf("Round-trip failed. Original: %v, Decrypted: %v", data, decrypted)
   405  			}
   406  		})
   407  
   408  		t.Run("ECDSA", func(t *testing.T) {
   409  			ecdsaKeys, err := algo.GenerateECDSAKeyPair(algo.P256)
   410  			if err != nil {
   411  				t.Fatalf("Failed to generate ECDSA key pair: %v", err)
   412  			}
   413  
   414  			encrypted, err := Encrypt(data, ecdsaKeys, opts)
   415  			if err != nil {
   416  				t.Fatalf("Failed to encrypt: %v", err)
   417  			}
   418  
   419  			decrypted, err := Decrypt(encrypted, ecdsaKeys, decryptOpts)
   420  			if err != nil {
   421  				t.Fatalf("Failed to decrypt: %v", err)
   422  			}
   423  
   424  			if string(decrypted) != string(data) {
   425  				t.Errorf("Round-trip failed. Original: %v, Decrypted: %v", data, decrypted)
   426  			}
   427  		})
   428  
   429  		t.Run("Ed25519", func(t *testing.T) {
   430  			ed25519Keys, err := algo.GenerateEd25519KeyPair()
   431  			if err != nil {
   432  				t.Fatalf("Failed to generate Ed25519 key pair: %v", err)
   433  			}
   434  
   435  			encrypted, err := Encrypt(data, ed25519Keys, opts)
   436  			if err != nil {
   437  				t.Fatalf("Failed to encrypt: %v", err)
   438  			}
   439  
   440  			decrypted, err := Decrypt(encrypted, ed25519Keys, decryptOpts)
   441  			if err != nil {
   442  				t.Fatalf("Failed to decrypt: %v", err)
   443  			}
   444  
   445  			if string(decrypted) != string(data) {
   446  				t.Errorf("Round-trip failed. Original: %v, Decrypted: %v", data, decrypted)
   447  			}
   448  		})
   449  	}
   450  }
   451  
   452  // Tests for ephemeral key utilities
   453  
   454  func TestGenerateEphemeralECDSAKey(t *testing.T) {
   455  	// Generate recipient key pair
   456  	recipientKeys, err := algo.GenerateECDSAKeyPair(algo.P256)
   457  	if err != nil {
   458  		t.Fatalf("Failed to generate recipient key: %v", err)
   459  	}
   460  
   461  	t.Run("Valid P256 key", func(t *testing.T) {
   462  		ephemeralKey, err := generateEphemeralECDSAKey(recipientKeys.PublicKey)
   463  		if err != nil {
   464  			t.Fatalf("Failed to generate ephemeral key: %v", err)
   465  		}
   466  
   467  		if ephemeralKey == nil {
   468  			t.Fatal("Ephemeral key is nil")
   469  		}
   470  
   471  		if ephemeralKey.Curve != recipientKeys.PublicKey.Curve {
   472  			t.Error("Ephemeral key curve doesn't match recipient key curve")
   473  		}
   474  	})
   475  
   476  	t.Run("Nil recipient key", func(t *testing.T) {
   477  		_, err := generateEphemeralECDSAKey(nil)
   478  		if err == nil {
   479  			t.Fatal("Expected error for nil recipient key")
   480  		}
   481  	})
   482  }
   483  
   484  func TestGenerateEphemeralX25519Key(t *testing.T) {
   485  	ephemeralKey, err := generateEphemeralX25519Key()
   486  	if err != nil {
   487  		t.Fatalf("Failed to generate ephemeral X25519 key: %v", err)
   488  	}
   489  
   490  	if ephemeralKey == nil {
   491  		t.Fatal("Ephemeral key is nil")
   492  	}
   493  
   494  	// Test that we can get the public key
   495  	publicKeyBytes := ephemeralKey.PublicKey().Bytes()
   496  	if len(publicKeyBytes) != 32 {
   497  		t.Errorf("Expected 32-byte X25519 public key, got %d bytes", len(publicKeyBytes))
   498  	}
   499  }
   500  
   501  func TestPerformECDHKeyAgreement(t *testing.T) {
   502  	// Generate two key pairs for testing
   503  	aliceKeys, err := algo.GenerateECDSAKeyPair(algo.P256)
   504  	if err != nil {
   505  		t.Fatalf("Failed to generate Alice's key: %v", err)
   506  	}
   507  
   508  	bobKeys, err := algo.GenerateECDSAKeyPair(algo.P256)
   509  	if err != nil {
   510  		t.Fatalf("Failed to generate Bob's key: %v", err)
   511  	}
   512  
   513  	t.Run("Valid key agreement", func(t *testing.T) {
   514  		// Alice computes shared secret using her private key and Bob's public key
   515  		sharedSecretAlice, err := performECDHKeyAgreement(aliceKeys.PrivateKey, bobKeys.PublicKey)
   516  		if err != nil {
   517  			t.Fatalf("Alice's key agreement failed: %v", err)
   518  		}
   519  
   520  		// Bob computes shared secret using his private key and Alice's public key
   521  		sharedSecretBob, err := performECDHKeyAgreement(bobKeys.PrivateKey, aliceKeys.PublicKey)
   522  		if err != nil {
   523  			t.Fatalf("Bob's key agreement failed: %v", err)
   524  		}
   525  
   526  		// Both should compute the same shared secret
   527  		if len(sharedSecretAlice) == 0 || len(sharedSecretBob) == 0 {
   528  			t.Fatal("Shared secrets are empty")
   529  		}
   530  
   531  		if string(sharedSecretAlice) != string(sharedSecretBob) {
   532  			t.Error("Shared secrets don't match")
   533  		}
   534  	})
   535  
   536  	t.Run("Nil keys", func(t *testing.T) {
   537  		_, err := performECDHKeyAgreement(nil, bobKeys.PublicKey)
   538  		if err == nil {
   539  			t.Error("Expected error for nil private key")
   540  		}
   541  
   542  		_, err = performECDHKeyAgreement(aliceKeys.PrivateKey, nil)
   543  		if err == nil {
   544  			t.Error("Expected error for nil public key")
   545  		}
   546  	})
   547  
   548  	t.Run("Curve mismatch", func(t *testing.T) {
   549  		// Generate key with different curve
   550  		p384Keys, err := algo.GenerateECDSAKeyPair(algo.P384)
   551  		if err != nil {
   552  			t.Fatalf("Failed to generate P384 key: %v", err)
   553  		}
   554  
   555  		_, err = performECDHKeyAgreement(aliceKeys.PrivateKey, p384Keys.PublicKey)
   556  		if err == nil {
   557  			t.Error("Expected error for curve mismatch")
   558  		}
   559  	})
   560  }
   561  
   562  func TestPerformX25519KeyAgreement(t *testing.T) {
   563  	// Generate two X25519 key pairs
   564  	aliceKey, err := generateEphemeralX25519Key()
   565  	if err != nil {
   566  		t.Fatalf("Failed to generate Alice's X25519 key: %v", err)
   567  	}
   568  
   569  	bobKey, err := generateEphemeralX25519Key()
   570  	if err != nil {
   571  		t.Fatalf("Failed to generate Bob's X25519 key: %v", err)
   572  	}
   573  
   574  	t.Run("Valid key agreement", func(t *testing.T) {
   575  		// Alice computes shared secret
   576  		sharedSecretAlice, err := performX25519KeyAgreement(aliceKey, bobKey.PublicKey().Bytes())
   577  		if err != nil {
   578  			t.Fatalf("Alice's X25519 key agreement failed: %v", err)
   579  		}
   580  
   581  		// Bob computes shared secret
   582  		sharedSecretBob, err := performX25519KeyAgreement(bobKey, aliceKey.PublicKey().Bytes())
   583  		if err != nil {
   584  			t.Fatalf("Bob's X25519 key agreement failed: %v", err)
   585  		}
   586  
   587  		// Both should compute the same shared secret
   588  		if len(sharedSecretAlice) == 0 || len(sharedSecretBob) == 0 {
   589  			t.Fatal("Shared secrets are empty")
   590  		}
   591  
   592  		if string(sharedSecretAlice) != string(sharedSecretBob) {
   593  			t.Error("Shared secrets don't match")
   594  		}
   595  	})
   596  
   597  	t.Run("Invalid public key length", func(t *testing.T) {
   598  		invalidKey := make([]byte, 16) // Wrong length
   599  		_, err := performX25519KeyAgreement(aliceKey, invalidKey)
   600  		if err == nil {
   601  			t.Error("Expected error for invalid key length")
   602  		}
   603  	})
   604  
   605  	t.Run("Nil private key", func(t *testing.T) {
   606  		_, err := performX25519KeyAgreement(nil, bobKey.PublicKey().Bytes())
   607  		if err == nil {
   608  			t.Error("Expected error for nil private key")
   609  		}
   610  	})
   611  }
   612  
   613  func TestDeriveAESKeyFromSharedSecret(t *testing.T) {
   614  	sharedSecret := []byte("this is a test shared secret for key derivation")
   615  	info := []byte("GoPKI-encryption-test")
   616  
   617  	t.Run("Valid derivation", func(t *testing.T) {
   618  		aesKey, err := deriveAESKeyFromSharedSecret(sharedSecret, info)
   619  		if err != nil {
   620  			t.Fatalf("Failed to derive AES key: %v", err)
   621  		}
   622  
   623  		if len(aesKey) != 32 {
   624  			t.Errorf("Expected 32-byte AES key, got %d bytes", len(aesKey))
   625  		}
   626  
   627  		// Test deterministic behavior - same inputs should produce same output
   628  		aesKey2, err := deriveAESKeyFromSharedSecret(sharedSecret, info)
   629  		if err != nil {
   630  			t.Fatalf("Failed to derive AES key second time: %v", err)
   631  		}
   632  
   633  		if string(aesKey) != string(aesKey2) {
   634  			t.Error("Key derivation is not deterministic")
   635  		}
   636  	})
   637  
   638  	t.Run("Different info produces different keys", func(t *testing.T) {
   639  		aesKey1, err := deriveAESKeyFromSharedSecret(sharedSecret, []byte("info1"))
   640  		if err != nil {
   641  			t.Fatalf("Failed to derive AES key 1: %v", err)
   642  		}
   643  
   644  		aesKey2, err := deriveAESKeyFromSharedSecret(sharedSecret, []byte("info2"))
   645  		if err != nil {
   646  			t.Fatalf("Failed to derive AES key 2: %v", err)
   647  		}
   648  
   649  		if string(aesKey1) == string(aesKey2) {
   650  			t.Error("Different info should produce different keys")
   651  		}
   652  	})
   653  
   654  	t.Run("Empty shared secret", func(t *testing.T) {
   655  		_, err := deriveAESKeyFromSharedSecret([]byte{}, info)
   656  		if err == nil {
   657  			t.Error("Expected error for empty shared secret")
   658  		}
   659  	})
   660  }
   661  
   662  // Ed25519 to X25519 conversion tests removed - functionality disabled due to key derivation incompatibility
   663  
   664  // Integration tests for EncryptForPublicKey → DecryptWithPrivateKey round trips
   665  func TestEncryptForPublicKeyRoundTrip(t *testing.T) {
   666  	testData := [][]byte{
   667  		[]byte("Hello, World!"),
   668  		[]byte(""),
   669  		[]byte("Large data content for testing encryption and decryption with multiple algorithms including ECDSA and Ed25519"),
   670  		make([]byte, 1024), // Large data
   671  	}
   672  
   673  	opts := encryption.DefaultEncryptOptions()
   674  	decryptOpts := encryption.DefaultDecryptOptions()
   675  
   676  	t.Run("RSA", func(t *testing.T) {
   677  		// Generate RSA key pair
   678  		rsaKeys, err := algo.GenerateRSAKeyPair(algo.KeySize2048)
   679  		if err != nil {
   680  			t.Fatalf("Failed to generate RSA key pair: %v", err)
   681  		}
   682  
   683  		for i, data := range testData {
   684  			if len(data) > 190 { // RSA size limit for 2048-bit key
   685  				continue // Skip large data for RSA
   686  			}
   687  
   688  			t.Run(fmt.Sprintf("Data%d", i), func(t *testing.T) {
   689  				// Encrypt with public key
   690  				encrypted, err := EncryptForPublicKey(data, rsaKeys.PublicKey, opts)
   691  				if err != nil {
   692  					t.Fatalf("Encryption failed: %v", err)
   693  				}
   694  
   695  				// Decrypt with private key
   696  				decrypted, err := DecryptWithPrivateKey(encrypted, rsaKeys.PrivateKey, decryptOpts)
   697  				if err != nil {
   698  					t.Fatalf("Decryption failed: %v", err)
   699  				}
   700  
   701  				// Verify data integrity
   702  				if !strings.EqualFold(string(data), string(decrypted)) {
   703  					t.Errorf("Data mismatch: expected %q, got %q", string(data), string(decrypted))
   704  				}
   705  
   706  				// Verify algorithm
   707  				if encrypted.Algorithm != encryption.AlgorithmRSAOAEP {
   708  					t.Errorf("Expected RSA-OAEP algorithm, got %s", encrypted.Algorithm)
   709  				}
   710  			})
   711  		}
   712  	})
   713  
   714  	t.Run("ECDSA", func(t *testing.T) {
   715  		curves := []algo.ECDSACurve{algo.P256, algo.P384, algo.P521}
   716  		curveNames := []string{"P256", "P384", "P521"}
   717  
   718  		for curveIdx, curve := range curves {
   719  			t.Run(curveNames[curveIdx], func(t *testing.T) {
   720  				// Generate ECDSA key pair
   721  				ecdsaKeys, err := algo.GenerateECDSAKeyPair(curve)
   722  				if err != nil {
   723  					t.Fatalf("Failed to generate ECDSA key pair: %v", err)
   724  				}
   725  
   726  				for i, data := range testData {
   727  					t.Run(fmt.Sprintf("Data%d", i), func(t *testing.T) {
   728  						// Encrypt with public key
   729  						encrypted, err := EncryptForPublicKey(data, ecdsaKeys.PublicKey, opts)
   730  						if err != nil {
   731  							t.Fatalf("Encryption failed: %v", err)
   732  						}
   733  
   734  						// Decrypt with private key
   735  						decrypted, err := DecryptWithPrivateKey(encrypted, ecdsaKeys.PrivateKey, decryptOpts)
   736  						if err != nil {
   737  							t.Fatalf("Decryption failed: %v", err)
   738  						}
   739  
   740  						// Verify data integrity
   741  						if !strings.EqualFold(string(data), string(decrypted)) {
   742  							t.Errorf("Data mismatch: expected %q, got %q", string(data), string(decrypted))
   743  						}
   744  
   745  						// Verify algorithm
   746  						if encrypted.Algorithm != encryption.AlgorithmECDH {
   747  							t.Errorf("Expected ECDH algorithm, got %s", encrypted.Algorithm)
   748  						}
   749  
   750  						// Verify ephemeral key is present
   751  						if len(encrypted.EncryptedKey) == 0 {
   752  							t.Error("Ephemeral key missing from encrypted data")
   753  						}
   754  
   755  						// Verify IV and Tag are present
   756  						if len(encrypted.IV) == 0 {
   757  							t.Error("IV missing from encrypted data")
   758  						}
   759  						if len(encrypted.Tag) == 0 {
   760  							t.Error("Tag missing from encrypted data")
   761  						}
   762  					})
   763  				}
   764  			})
   765  		}
   766  	})
   767  
   768  	t.Run("Ed25519", func(t *testing.T) {
   769  		// Generate Ed25519 key pair
   770  		ed25519Keys, err := algo.GenerateEd25519KeyPair()
   771  		if err != nil {
   772  			t.Fatalf("Failed to generate Ed25519 key pair: %v", err)
   773  		}
   774  
   775  		for i, data := range testData {
   776  			t.Run(fmt.Sprintf("Data%d", i), func(t *testing.T) {
   777  				// Ed25519 public-key-only encryption has partial implementation (may fail with certain keys)
   778  				_, err := EncryptForPublicKey(data, ed25519Keys.PublicKey, opts)
   779  				if err == nil {
   780  					t.Logf("Ed25519 round-trip encryption succeeded for data size %d", len(data))
   781  				} else {
   782  					// This is expected with current implementation
   783  					if !strings.Contains(err.Error(), "Ed25519 public-key-only encryption failed") {
   784  						t.Errorf("Expected Ed25519 conversion error, got: %v", err)
   785  					}
   786  					t.Logf("Ed25519 round-trip encryption failed as expected for data size %d: %v", len(data), err)
   787  				}
   788  			})
   789  		}
   790  	})
   791  }
   792  
   793  // Test cross-key decryption should fail
   794  func TestEncryptForPublicKeyCrossKeyDecryption(t *testing.T) {
   795  	data := []byte("test data")
   796  	opts := encryption.DefaultEncryptOptions()
   797  	decryptOpts := encryption.DefaultDecryptOptions()
   798  
   799  	// Generate different key pairs
   800  	ecdsaKeys1, _ := algo.GenerateECDSAKeyPair(algo.P256)
   801  	ecdsaKeys2, _ := algo.GenerateECDSAKeyPair(algo.P256)
   802  	ed25519Keys1, _ := algo.GenerateEd25519KeyPair()
   803  
   804  	t.Run("ECDSA cross-key", func(t *testing.T) {
   805  		// Encrypt with first key
   806  		encrypted, err := EncryptForPublicKey(data, ecdsaKeys1.PublicKey, opts)
   807  		if err != nil {
   808  			t.Fatalf("Encryption failed: %v", err)
   809  		}
   810  
   811  		// Try to decrypt with second key (should fail)
   812  		_, err = DecryptWithPrivateKey(encrypted, ecdsaKeys2.PrivateKey, decryptOpts)
   813  		if err == nil {
   814  			t.Error("Expected decryption to fail with wrong key")
   815  		}
   816  	})
   817  
   818  	t.Run("Ed25519 cross-key", func(t *testing.T) {
   819  		// Ed25519 public-key-only encryption has partial implementation (may fail with certain keys)
   820  		_, err := EncryptForPublicKey(data, ed25519Keys1.PublicKey, opts)
   821  		if err == nil {
   822  			t.Log("Ed25519 cross-key encryption succeeded (key format compatible)")
   823  		} else {
   824  			// This is expected with current implementation
   825  			if !strings.Contains(err.Error(), "Ed25519 public-key-only encryption failed") {
   826  				t.Errorf("Expected Ed25519 conversion error, got: %v", err)
   827  			}
   828  			t.Logf("Ed25519 cross-key test failed as expected: %v", err)
   829  		}
   830  	})
   831  }
   832  
   833  // Test algorithm mismatch should fail
   834  func TestEncryptForPublicKeyAlgorithmMismatch(t *testing.T) {
   835  	decryptOpts := encryption.DefaultDecryptOptions()
   836  
   837  	// Generate key pairs
   838  	rsaKeys, _ := algo.GenerateRSAKeyPair(algo.KeySize2048)
   839  	ecdsaKeys, _ := algo.GenerateECDSAKeyPair(algo.P256)
   840  	ed25519Keys, _ := algo.GenerateEd25519KeyPair()
   841  
   842  	t.Run("RSA key with ECDH algorithm", func(t *testing.T) {
   843  		// Create fake encrypted data with wrong algorithm
   844  		encrypted := &encryption.EncryptedData{
   845  			Algorithm: encryption.AlgorithmECDH,
   846  			Data:      []byte("fake data"),
   847  		}
   848  
   849  		// Try to decrypt with RSA key (should fail)
   850  		_, err := DecryptWithPrivateKey(encrypted, rsaKeys.PrivateKey, decryptOpts)
   851  		if err == nil {
   852  			t.Error("Expected decryption to fail with algorithm mismatch")
   853  		}
   854  	})
   855  
   856  	t.Run("ECDSA key with X25519 algorithm", func(t *testing.T) {
   857  		// Create fake encrypted data with wrong algorithm
   858  		encrypted := &encryption.EncryptedData{
   859  			Algorithm: encryption.AlgorithmX25519,
   860  			Data:      []byte("fake data"),
   861  		}
   862  
   863  		// Try to decrypt with ECDSA key (should fail)
   864  		_, err := DecryptWithPrivateKey(encrypted, ecdsaKeys.PrivateKey, decryptOpts)
   865  		if err == nil {
   866  			t.Error("Expected decryption to fail with algorithm mismatch")
   867  		}
   868  	})
   869  
   870  	t.Run("Ed25519 key with ECDH algorithm", func(t *testing.T) {
   871  		// Create fake encrypted data with wrong algorithm
   872  		encrypted := &encryption.EncryptedData{
   873  			Algorithm: encryption.AlgorithmECDH,
   874  			Data:      []byte("fake data"),
   875  		}
   876  
   877  		// Try to decrypt with Ed25519 key (should fail)
   878  		_, err := DecryptWithPrivateKey(encrypted, ed25519Keys.PrivateKey, decryptOpts)
   879  		if err == nil {
   880  			t.Error("Expected decryption to fail with algorithm mismatch")
   881  		}
   882  	})
   883  }