github.com/jasoet/gopki@v1.15.0/encryption/asymmetric/ed25519_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 TestEncryptWithEd25519(t *testing.T) {
    13  	ed25519Keys, err := algo.GenerateEd25519KeyPair()
    14  	if err != nil {
    15  		t.Fatalf("Failed to generate Ed25519 key pair: %v", err)
    16  	}
    17  
    18  	opts := encryption.DefaultEncryptOptions()
    19  
    20  	t.Run("ValidData", func(t *testing.T) {
    21  		data := []byte("test data for Ed25519 encryption")
    22  
    23  		encrypted, err := EncryptWithEd25519(data, ed25519Keys, opts)
    24  		if err != nil {
    25  			t.Fatalf("Failed to encrypt with Ed25519: %v", err)
    26  		}
    27  
    28  		if encrypted == nil {
    29  			t.Fatal("Encrypted data is nil")
    30  		}
    31  		if encrypted.Algorithm != encryption.AlgorithmX25519 {
    32  			t.Errorf("Expected algorithm %s, got %s", encryption.AlgorithmX25519, encrypted.Algorithm)
    33  		}
    34  		if len(encrypted.Data) == 0 {
    35  			t.Error("Encrypted data is empty")
    36  		}
    37  		if len(encrypted.EncryptedKey) == 0 {
    38  			t.Error("Ephemeral public key should be stored in EncryptedKey")
    39  		}
    40  		if len(encrypted.IV) == 0 {
    41  			t.Error("IV should be present")
    42  		}
    43  		if len(encrypted.Tag) == 0 {
    44  			t.Error("Authentication tag should be present")
    45  		}
    46  		if encrypted.Timestamp.IsZero() {
    47  			t.Error("Timestamp should be set")
    48  		}
    49  		if encrypted.Format != opts.Format {
    50  			t.Errorf("Expected format %s, got %s", opts.Format, encrypted.Format)
    51  		}
    52  	})
    53  
    54  	t.Run("EmptyData", func(t *testing.T) {
    55  		data := []byte("")
    56  
    57  		encrypted, err := EncryptWithEd25519(data, ed25519Keys, opts)
    58  		if err != nil {
    59  			t.Fatalf("Failed to encrypt empty data: %v", err)
    60  		}
    61  
    62  		if encrypted == nil {
    63  			t.Fatal("Encrypted data is nil")
    64  		}
    65  	})
    66  
    67  	t.Run("LargeData", func(t *testing.T) {
    68  		// Ed25519 with AES-GCM can handle large data
    69  		largeData := make([]byte, 100000)
    70  		for i := range largeData {
    71  			largeData[i] = byte(i % 256)
    72  		}
    73  
    74  		encrypted, err := EncryptWithEd25519(largeData, ed25519Keys, opts)
    75  		if err != nil {
    76  			t.Fatalf("Failed to encrypt large data: %v", err)
    77  		}
    78  
    79  		if encrypted == nil {
    80  			t.Fatal("Encrypted data is nil")
    81  		}
    82  		if len(encrypted.Data) == 0 {
    83  			t.Error("Encrypted data should not be empty for large input")
    84  		}
    85  	})
    86  
    87  	t.Run("InvalidOptions", func(t *testing.T) {
    88  		data := []byte("test data")
    89  		invalidOpts := encryption.EncryptOptions{
    90  			Algorithm: "invalid",
    91  			Format:    encryption.FormatCMS,
    92  		}
    93  
    94  		_, err := EncryptWithEd25519(data, ed25519Keys, invalidOpts)
    95  		if err == nil {
    96  			t.Error("Expected error for invalid options")
    97  		}
    98  	})
    99  }
   100  
   101  func TestDecryptWithEd25519(t *testing.T) {
   102  	ed25519Keys, err := algo.GenerateEd25519KeyPair()
   103  	if err != nil {
   104  		t.Fatalf("Failed to generate Ed25519 key pair: %v", err)
   105  	}
   106  
   107  	opts := encryption.DefaultEncryptOptions()
   108  	decryptOpts := encryption.DefaultDecryptOptions()
   109  	data := []byte("test data for Ed25519 decryption")
   110  
   111  	t.Run("ValidDecryption", func(t *testing.T) {
   112  		encrypted, err := EncryptWithEd25519(data, ed25519Keys, opts)
   113  		if err != nil {
   114  			t.Fatalf("Failed to encrypt: %v", err)
   115  		}
   116  
   117  		decrypted, err := DecryptWithEd25519(encrypted, ed25519Keys, decryptOpts)
   118  		if err != nil {
   119  			t.Fatalf("Failed to decrypt: %v", err)
   120  		}
   121  
   122  		if string(decrypted) != string(data) {
   123  			t.Errorf("Decrypted data doesn't match. Expected: %s, Got: %s", string(data), string(decrypted))
   124  		}
   125  	})
   126  
   127  	t.Run("WrongAlgorithm", func(t *testing.T) {
   128  		encrypted := &encryption.EncryptedData{
   129  			Algorithm: encryption.AlgorithmECDH, // Wrong algorithm
   130  			Data:      []byte("encrypted"),
   131  		}
   132  
   133  		_, err := DecryptWithEd25519(encrypted, ed25519Keys, decryptOpts)
   134  		if err == nil {
   135  			t.Error("Expected error for wrong algorithm")
   136  		}
   137  		if !strings.Contains(err.Error(), "expected X25519") {
   138  			t.Errorf("Expected algorithm error, got: %v", err)
   139  		}
   140  	})
   141  
   142  	t.Run("InvalidEphemeralKey", func(t *testing.T) {
   143  		encrypted, err := EncryptWithEd25519(data, ed25519Keys, opts)
   144  		if err != nil {
   145  			t.Fatalf("Failed to encrypt: %v", err)
   146  		}
   147  
   148  		// Corrupt the ephemeral key
   149  		encrypted.EncryptedKey = []byte("invalid ephemeral key")
   150  
   151  		_, err = DecryptWithEd25519(encrypted, ed25519Keys, decryptOpts)
   152  		if err == nil {
   153  			t.Error("Expected error for invalid ephemeral key")
   154  		}
   155  	})
   156  
   157  	t.Run("CorruptedData", func(t *testing.T) {
   158  		encrypted, err := EncryptWithEd25519(data, ed25519Keys, opts)
   159  		if err != nil {
   160  			t.Fatalf("Failed to encrypt: %v", err)
   161  		}
   162  
   163  		// Corrupt the encrypted data
   164  		encrypted.Data[0] ^= 0xFF
   165  
   166  		_, err = DecryptWithEd25519(encrypted, ed25519Keys, decryptOpts)
   167  		if err == nil {
   168  			t.Error("Expected error for corrupted data")
   169  		}
   170  	})
   171  
   172  	t.Run("CorruptedIV", func(t *testing.T) {
   173  		encrypted, err := EncryptWithEd25519(data, ed25519Keys, opts)
   174  		if err != nil {
   175  			t.Fatalf("Failed to encrypt: %v", err)
   176  		}
   177  
   178  		// Corrupt the IV
   179  		encrypted.IV[0] ^= 0xFF
   180  
   181  		_, err = DecryptWithEd25519(encrypted, ed25519Keys, decryptOpts)
   182  		if err == nil {
   183  			t.Error("Expected error for corrupted IV")
   184  		}
   185  	})
   186  
   187  	t.Run("CorruptedTag", func(t *testing.T) {
   188  		encrypted, err := EncryptWithEd25519(data, ed25519Keys, opts)
   189  		if err != nil {
   190  			t.Fatalf("Failed to encrypt: %v", err)
   191  		}
   192  
   193  		// Corrupt the authentication tag
   194  		encrypted.Tag[0] ^= 0xFF
   195  
   196  		_, err = DecryptWithEd25519(encrypted, ed25519Keys, decryptOpts)
   197  		if err == nil {
   198  			t.Error("Expected error for corrupted authentication tag")
   199  		}
   200  	})
   201  
   202  	t.Run("WrongKeyPair", func(t *testing.T) {
   203  		// Generate different key pair
   204  		wrongKeys, err := algo.GenerateEd25519KeyPair()
   205  		if err != nil {
   206  			t.Fatalf("Failed to generate wrong Ed25519 key pair: %v", err)
   207  		}
   208  
   209  		encrypted, err := EncryptWithEd25519(data, ed25519Keys, opts)
   210  		if err != nil {
   211  			t.Fatalf("Failed to encrypt: %v", err)
   212  		}
   213  
   214  		_, err = DecryptWithEd25519(encrypted, wrongKeys, decryptOpts)
   215  		if err == nil {
   216  			t.Error("Expected error for wrong key pair")
   217  		}
   218  	})
   219  
   220  	t.Run("InvalidDecryptOptions", func(t *testing.T) {
   221  		encrypted, err := EncryptWithEd25519(data, ed25519Keys, opts)
   222  		if err != nil {
   223  			t.Fatalf("Failed to encrypt: %v", err)
   224  		}
   225  
   226  		invalidDecryptOpts := encryption.DecryptOptions{
   227  			MaxAge: -1, // Invalid negative max age
   228  		}
   229  
   230  		_, err = DecryptWithEd25519(encrypted, ed25519Keys, invalidDecryptOpts)
   231  		if err == nil {
   232  			t.Error("Expected error for invalid decrypt options")
   233  		}
   234  	})
   235  }
   236  
   237  func TestEd25519RoundTrip(t *testing.T) {
   238  	ed25519Keys, err := algo.GenerateEd25519KeyPair()
   239  	if err != nil {
   240  		t.Fatalf("Failed to generate Ed25519 key pair: %v", err)
   241  	}
   242  
   243  	dataSizes := []int{0, 1, 16, 100, 1024, 10000, 100000}
   244  	opts := encryption.DefaultEncryptOptions()
   245  	decryptOpts := encryption.DefaultDecryptOptions()
   246  
   247  	for _, size := range dataSizes {
   248  		t.Run(fmt.Sprintf("Size%d", size), func(t *testing.T) {
   249  			data := make([]byte, size)
   250  			for i := range data {
   251  				data[i] = byte(i % 256)
   252  			}
   253  
   254  			encrypted, err := EncryptWithEd25519(data, ed25519Keys, opts)
   255  			if err != nil {
   256  				t.Fatalf("Failed to encrypt %d bytes: %v", size, err)
   257  			}
   258  
   259  			decrypted, err := DecryptWithEd25519(encrypted, ed25519Keys, decryptOpts)
   260  			if err != nil {
   261  				t.Fatalf("Failed to decrypt %d bytes: %v", size, err)
   262  			}
   263  
   264  			if len(decrypted) != len(data) {
   265  				t.Errorf("Length mismatch. Expected: %d, Got: %d", len(data), len(decrypted))
   266  			}
   267  
   268  			for i := range data {
   269  				if decrypted[i] != data[i] {
   270  					t.Errorf("Data mismatch at position %d. Expected: %d, Got: %d", i, data[i], decrypted[i])
   271  					break
   272  				}
   273  			}
   274  		})
   275  	}
   276  }
   277  
   278  func TestEd25519WithMetadata(t *testing.T) {
   279  	ed25519Keys, err := algo.GenerateEd25519KeyPair()
   280  	if err != nil {
   281  		t.Fatalf("Failed to generate Ed25519 key pair: %v", err)
   282  	}
   283  
   284  	data := []byte("test data with metadata")
   285  	opts := encryption.EncryptOptions{
   286  		Algorithm: encryption.AlgorithmX25519,
   287  		Format:    encryption.FormatCMS,
   288  		Metadata: map[string]interface{}{
   289  			"algorithm": "Ed25519",
   290  			"version":   1,
   291  			"test_data": map[string]interface{}{
   292  				"size": len(data),
   293  				"type": "string",
   294  			},
   295  		},
   296  	}
   297  
   298  	encrypted, err := EncryptWithEd25519(data, ed25519Keys, opts)
   299  	if err != nil {
   300  		t.Fatalf("Failed to encrypt: %v", err)
   301  	}
   302  
   303  	if encrypted.Metadata == nil {
   304  		t.Error("Metadata should be preserved")
   305  	}
   306  
   307  	if val, ok := encrypted.Metadata["algorithm"]; !ok || val != "Ed25519" {
   308  		t.Error("String metadata not preserved correctly")
   309  	}
   310  
   311  	if val, ok := encrypted.Metadata["version"]; !ok || val != 1 {
   312  		t.Error("Numeric metadata not preserved correctly")
   313  	}
   314  
   315  	if testData, ok := encrypted.Metadata["test_data"].(map[string]interface{}); !ok {
   316  		t.Error("Nested metadata not preserved correctly")
   317  	} else {
   318  		if size, ok := testData["size"]; !ok || size != len(data) {
   319  			t.Error("Nested size metadata not preserved correctly")
   320  		}
   321  		if typ, ok := testData["type"]; !ok || typ != "string" {
   322  			t.Error("Nested type metadata not preserved correctly")
   323  		}
   324  	}
   325  }
   326  
   327  func TestEd25519KeyDerivation(t *testing.T) {
   328  	// Test that Ed25519 to X25519 key derivation is consistent
   329  	ed25519Keys, err := algo.GenerateEd25519KeyPair()
   330  	if err != nil {
   331  		t.Fatalf("Failed to generate Ed25519 key pair: %v", err)
   332  	}
   333  
   334  	data := []byte("test key derivation consistency")
   335  	opts := encryption.DefaultEncryptOptions()
   336  
   337  	// Encrypt multiple times with the same key pair
   338  	encrypted1, err := EncryptWithEd25519(data, ed25519Keys, opts)
   339  	if err != nil {
   340  		t.Fatalf("Failed to encrypt first time: %v", err)
   341  	}
   342  
   343  	encrypted2, err := EncryptWithEd25519(data, ed25519Keys, opts)
   344  	if err != nil {
   345  		t.Fatalf("Failed to encrypt second time: %v", err)
   346  	}
   347  
   348  	// The ephemeral keys should be different (for forward secrecy)
   349  	if string(encrypted1.EncryptedKey) == string(encrypted2.EncryptedKey) {
   350  		t.Error("Ephemeral keys should be different for forward secrecy")
   351  	}
   352  
   353  	// But both should decrypt correctly with the same private key
   354  	decrypted1, err := DecryptWithEd25519(encrypted1, ed25519Keys, encryption.DefaultDecryptOptions())
   355  	if err != nil {
   356  		t.Fatalf("Failed to decrypt first encryption: %v", err)
   357  	}
   358  
   359  	decrypted2, err := DecryptWithEd25519(encrypted2, ed25519Keys, encryption.DefaultDecryptOptions())
   360  	if err != nil {
   361  		t.Fatalf("Failed to decrypt second encryption: %v", err)
   362  	}
   363  
   364  	if string(decrypted1) != string(data) {
   365  		t.Error("First decryption failed")
   366  	}
   367  
   368  	if string(decrypted2) != string(data) {
   369  		t.Error("Second decryption failed")
   370  	}
   371  }
   372  
   373  func TestEd25519EphemeralKeyGeneration(t *testing.T) {
   374  	ed25519Keys, err := algo.GenerateEd25519KeyPair()
   375  	if err != nil {
   376  		t.Fatalf("Failed to generate Ed25519 key pair: %v", err)
   377  	}
   378  
   379  	data := []byte("test ephemeral key generation")
   380  	opts := encryption.DefaultEncryptOptions()
   381  
   382  	// Generate multiple encryptions to test ephemeral key generation
   383  	ephemeralKeys := make(map[string]bool)
   384  	numTests := 10
   385  
   386  	for i := 0; i < numTests; i++ {
   387  		encrypted, err := EncryptWithEd25519(data, ed25519Keys, opts)
   388  		if err != nil {
   389  			t.Fatalf("Failed to encrypt iteration %d: %v", i, err)
   390  		}
   391  
   392  		// Check ephemeral key length (should be 32 bytes for X25519)
   393  		if len(encrypted.EncryptedKey) != 32 {
   394  			t.Errorf("Expected ephemeral key length 32, got %d", len(encrypted.EncryptedKey))
   395  		}
   396  
   397  		// Check for uniqueness
   398  		keyStr := string(encrypted.EncryptedKey)
   399  		if ephemeralKeys[keyStr] {
   400  			t.Error("Ephemeral key collision detected - keys should be unique")
   401  		}
   402  		ephemeralKeys[keyStr] = true
   403  
   404  		// Verify decryption works
   405  		decrypted, err := DecryptWithEd25519(encrypted, ed25519Keys, encryption.DefaultDecryptOptions())
   406  		if err != nil {
   407  			t.Fatalf("Failed to decrypt iteration %d: %v", i, err)
   408  		}
   409  
   410  		if string(decrypted) != string(data) {
   411  			t.Errorf("Decryption failed for iteration %d", i)
   412  		}
   413  	}
   414  
   415  	// Verify we got unique ephemeral keys
   416  	if len(ephemeralKeys) != numTests {
   417  		t.Errorf("Expected %d unique ephemeral keys, got %d", numTests, len(ephemeralKeys))
   418  	}
   419  }
   420  
   421  func TestEd25519CrossKeyDecryption(t *testing.T) {
   422  	// Test that data encrypted with one Ed25519 key cannot be decrypted with another
   423  	key1, err := algo.GenerateEd25519KeyPair()
   424  	if err != nil {
   425  		t.Fatalf("Failed to generate first Ed25519 key pair: %v", err)
   426  	}
   427  
   428  	key2, err := algo.GenerateEd25519KeyPair()
   429  	if err != nil {
   430  		t.Fatalf("Failed to generate second Ed25519 key pair: %v", err)
   431  	}
   432  
   433  	data := []byte("test cross-key decryption protection")
   434  	opts := encryption.DefaultEncryptOptions()
   435  
   436  	// Encrypt with key1
   437  	encrypted, err := EncryptWithEd25519(data, key1, opts)
   438  	if err != nil {
   439  		t.Fatalf("Failed to encrypt with key1: %v", err)
   440  	}
   441  
   442  	// Try to decrypt with key2 (should fail)
   443  	_, err = DecryptWithEd25519(encrypted, key2, encryption.DefaultDecryptOptions())
   444  	if err == nil {
   445  		t.Error("Expected error when decrypting with wrong key pair")
   446  	}
   447  
   448  	// Verify key1 can still decrypt correctly
   449  	decrypted, err := DecryptWithEd25519(encrypted, key1, encryption.DefaultDecryptOptions())
   450  	if err != nil {
   451  		t.Fatalf("Failed to decrypt with correct key: %v", err)
   452  	}
   453  
   454  	if string(decrypted) != string(data) {
   455  		t.Error("Decryption with correct key failed")
   456  	}
   457  }