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

     1  package asymmetric
     2  
     3  import (
     4  	"strings"
     5  	"testing"
     6  
     7  	"github.com/jasoet/gopki/encryption"
     8  	"github.com/jasoet/gopki/keypair/algo"
     9  )
    10  
    11  func TestEncryptWithRSA(t *testing.T) {
    12  	rsaKeys, err := algo.GenerateRSAKeyPair(algo.KeySize2048)
    13  	if err != nil {
    14  		t.Fatalf("Failed to generate RSA key pair: %v", err)
    15  	}
    16  
    17  	opts := encryption.DefaultEncryptOptions()
    18  
    19  	t.Run("ValidData", func(t *testing.T) {
    20  		data := []byte("test data for RSA encryption")
    21  
    22  		encrypted, err := EncryptWithRSA(data, rsaKeys, opts)
    23  		if err != nil {
    24  			t.Fatalf("Failed to encrypt with RSA: %v", err)
    25  		}
    26  
    27  		if encrypted == nil {
    28  			t.Fatal("Encrypted data is nil")
    29  		}
    30  		if encrypted.Algorithm != encryption.AlgorithmRSAOAEP {
    31  			t.Errorf("Expected algorithm %s, got %s", encryption.AlgorithmRSAOAEP, encrypted.Algorithm)
    32  		}
    33  		if len(encrypted.Data) == 0 {
    34  			t.Error("Encrypted data is empty")
    35  		}
    36  		if encrypted.Format != opts.Format {
    37  			t.Errorf("Expected format %s, got %s", opts.Format, encrypted.Format)
    38  		}
    39  		if encrypted.Timestamp.IsZero() {
    40  			t.Error("Timestamp should be set")
    41  		}
    42  	})
    43  
    44  	t.Run("EmptyData", func(t *testing.T) {
    45  		data := []byte("")
    46  
    47  		encrypted, err := EncryptWithRSA(data, rsaKeys, opts)
    48  		if err != nil {
    49  			t.Fatalf("Failed to encrypt empty data: %v", err)
    50  		}
    51  
    52  		if encrypted == nil {
    53  			t.Fatal("Encrypted data is nil")
    54  		}
    55  		if len(encrypted.Data) == 0 {
    56  			t.Error("Encrypted data should not be empty even for empty input")
    57  		}
    58  	})
    59  
    60  	t.Run("LargeData", func(t *testing.T) {
    61  		// RSA-OAEP with 2048-bit key can handle about 190 bytes max
    62  		// Let's test with data that's too large
    63  		largeData := make([]byte, 300) // Too large for RSA-2048
    64  		for i := range largeData {
    65  			largeData[i] = byte(i % 256)
    66  		}
    67  
    68  		_, err := EncryptWithRSA(largeData, rsaKeys, opts)
    69  		if err == nil {
    70  			t.Error("Expected error for data too large for RSA")
    71  		}
    72  		if !strings.Contains(err.Error(), "data size") {
    73  			t.Errorf("Expected data size error, got: %v", err)
    74  		}
    75  	})
    76  
    77  	t.Run("MaxSizeData", func(t *testing.T) {
    78  		// Test with data that's at the maximum size for RSA-2048
    79  		// For 2048-bit RSA with OAEP-SHA256, max data size is key_size - 2*hash_size - 2
    80  		// = 256 - 2*32 - 2 = 190 bytes
    81  		maxData := make([]byte, 190)
    82  		for i := range maxData {
    83  			maxData[i] = byte(i % 256)
    84  		}
    85  
    86  		encrypted, err := EncryptWithRSA(maxData, rsaKeys, opts)
    87  		if err != nil {
    88  			t.Fatalf("Failed to encrypt max size data: %v", err)
    89  		}
    90  
    91  		if encrypted == nil {
    92  			t.Fatal("Encrypted data is nil")
    93  		}
    94  	})
    95  
    96  	t.Run("InvalidOptions", func(t *testing.T) {
    97  		data := []byte("test data")
    98  		invalidOpts := encryption.EncryptOptions{
    99  			Algorithm: "invalid",
   100  			Format:    encryption.FormatCMS,
   101  		}
   102  
   103  		_, err := EncryptWithRSA(data, rsaKeys, invalidOpts)
   104  		if err == nil {
   105  			t.Error("Expected error for invalid options")
   106  		}
   107  	})
   108  }
   109  
   110  func TestDecryptWithRSA(t *testing.T) {
   111  	rsaKeys, err := algo.GenerateRSAKeyPair(algo.KeySize2048)
   112  	if err != nil {
   113  		t.Fatalf("Failed to generate RSA key pair: %v", err)
   114  	}
   115  
   116  	opts := encryption.DefaultEncryptOptions()
   117  	decryptOpts := encryption.DefaultDecryptOptions()
   118  	data := []byte("test data for RSA decryption")
   119  
   120  	t.Run("ValidDecryption", func(t *testing.T) {
   121  		encrypted, err := EncryptWithRSA(data, rsaKeys, opts)
   122  		if err != nil {
   123  			t.Fatalf("Failed to encrypt: %v", err)
   124  		}
   125  
   126  		decrypted, err := DecryptWithRSA(encrypted, rsaKeys, decryptOpts)
   127  		if err != nil {
   128  			t.Fatalf("Failed to decrypt: %v", err)
   129  		}
   130  
   131  		if string(decrypted) != string(data) {
   132  			t.Errorf("Decrypted data doesn't match. Expected: %s, Got: %s", string(data), string(decrypted))
   133  		}
   134  	})
   135  
   136  	t.Run("WrongAlgorithm", func(t *testing.T) {
   137  		encrypted := &encryption.EncryptedData{
   138  			Algorithm: encryption.AlgorithmECDH, // Wrong algorithm
   139  			Data:      []byte("encrypted"),
   140  		}
   141  
   142  		_, err := DecryptWithRSA(encrypted, rsaKeys, decryptOpts)
   143  		if err == nil {
   144  			t.Error("Expected error for wrong algorithm")
   145  		}
   146  		if !strings.Contains(err.Error(), "expected RSA-OAEP") {
   147  			t.Errorf("Expected algorithm error, got: %v", err)
   148  		}
   149  	})
   150  
   151  	t.Run("CorruptedData", func(t *testing.T) {
   152  		encrypted, err := EncryptWithRSA(data, rsaKeys, opts)
   153  		if err != nil {
   154  			t.Fatalf("Failed to encrypt: %v", err)
   155  		}
   156  
   157  		// Corrupt the encrypted data
   158  		encrypted.Data[0] ^= 0xFF
   159  
   160  		_, err = DecryptWithRSA(encrypted, rsaKeys, decryptOpts)
   161  		if err == nil {
   162  			t.Error("Expected error for corrupted data")
   163  		}
   164  	})
   165  
   166  	t.Run("WrongKeyPair", func(t *testing.T) {
   167  		// Generate different key pair
   168  		wrongKeys, err := algo.GenerateRSAKeyPair(algo.KeySize2048)
   169  		if err != nil {
   170  			t.Fatalf("Failed to generate wrong RSA key pair: %v", err)
   171  		}
   172  
   173  		encrypted, err := EncryptWithRSA(data, rsaKeys, opts)
   174  		if err != nil {
   175  			t.Fatalf("Failed to encrypt: %v", err)
   176  		}
   177  
   178  		_, err = DecryptWithRSA(encrypted, wrongKeys, decryptOpts)
   179  		if err == nil {
   180  			t.Error("Expected error for wrong key pair")
   181  		}
   182  	})
   183  
   184  	t.Run("InvalidDecryptOptions", func(t *testing.T) {
   185  		encrypted, err := EncryptWithRSA(data, rsaKeys, opts)
   186  		if err != nil {
   187  			t.Fatalf("Failed to encrypt: %v", err)
   188  		}
   189  
   190  		invalidDecryptOpts := encryption.DecryptOptions{
   191  			MaxAge: -1, // Invalid negative max age
   192  		}
   193  
   194  		_, err = DecryptWithRSA(encrypted, rsaKeys, invalidDecryptOpts)
   195  		if err == nil {
   196  			t.Error("Expected error for invalid decrypt options")
   197  		}
   198  	})
   199  }
   200  
   201  func TestRSARoundTrip(t *testing.T) {
   202  	testCases := []struct {
   203  		name     string
   204  		keySize  algo.KeySize
   205  		dataSize int
   206  	}{
   207  		{"RSA2048_Small", algo.KeySize2048, 10},
   208  		{"RSA2048_Medium", algo.KeySize2048, 100},
   209  		{"RSA2048_Max", algo.KeySize2048, 190}, // Max for 2048-bit RSA
   210  		{"RSA3072_Small", algo.KeySize3072, 10},
   211  		{"RSA3072_Medium", algo.KeySize3072, 200},
   212  		{"RSA3072_Max", algo.KeySize3072, 318}, // Max for 3072-bit RSA
   213  	}
   214  
   215  	opts := encryption.DefaultEncryptOptions()
   216  	decryptOpts := encryption.DefaultDecryptOptions()
   217  
   218  	for _, tc := range testCases {
   219  		t.Run(tc.name, func(t *testing.T) {
   220  			rsaKeys, err := algo.GenerateRSAKeyPair(tc.keySize)
   221  			if err != nil {
   222  				t.Fatalf("Failed to generate RSA %d key pair: %v", tc.keySize, err)
   223  			}
   224  
   225  			data := make([]byte, tc.dataSize)
   226  			for i := range data {
   227  				data[i] = byte(i % 256)
   228  			}
   229  
   230  			encrypted, err := EncryptWithRSA(data, rsaKeys, opts)
   231  			if err != nil {
   232  				t.Fatalf("Failed to encrypt: %v", err)
   233  			}
   234  
   235  			decrypted, err := DecryptWithRSA(encrypted, rsaKeys, decryptOpts)
   236  			if err != nil {
   237  				t.Fatalf("Failed to decrypt: %v", err)
   238  			}
   239  
   240  			if len(decrypted) != len(data) {
   241  				t.Errorf("Length mismatch. Expected: %d, Got: %d", len(data), len(decrypted))
   242  			}
   243  
   244  			for i := range data {
   245  				if decrypted[i] != data[i] {
   246  					t.Errorf("Data mismatch at position %d. Expected: %d, Got: %d", i, data[i], decrypted[i])
   247  					break
   248  				}
   249  			}
   250  		})
   251  	}
   252  }
   253  
   254  func TestRSADataSizeLimits(t *testing.T) {
   255  	testCases := []struct {
   256  		name     string
   257  		keySize  algo.KeySize
   258  		maxBytes int
   259  	}{
   260  		{"RSA2048", algo.KeySize2048, 190},
   261  		{"RSA3072", algo.KeySize3072, 318},
   262  		{"RSA4096", algo.KeySize4096, 446},
   263  	}
   264  
   265  	opts := encryption.DefaultEncryptOptions()
   266  
   267  	for _, tc := range testCases {
   268  		t.Run(tc.name, func(t *testing.T) {
   269  			rsaKeys, err := algo.GenerateRSAKeyPair(tc.keySize)
   270  			if err != nil {
   271  				t.Fatalf("Failed to generate RSA %d key pair: %v", tc.keySize, err)
   272  			}
   273  
   274  			// Test data at max size (should work)
   275  			maxData := make([]byte, tc.maxBytes)
   276  			_, err = EncryptWithRSA(maxData, rsaKeys, opts)
   277  			if err != nil {
   278  				t.Errorf("Failed to encrypt max size data (%d bytes): %v", tc.maxBytes, err)
   279  			}
   280  
   281  			// Test data over max size (should fail)
   282  			overMaxData := make([]byte, tc.maxBytes+1)
   283  			_, err = EncryptWithRSA(overMaxData, rsaKeys, opts)
   284  			if err == nil {
   285  				t.Errorf("Expected error for over-max size data (%d bytes)", tc.maxBytes+1)
   286  			}
   287  		})
   288  	}
   289  }
   290  
   291  func TestRSAWithMetadata(t *testing.T) {
   292  	rsaKeys, err := algo.GenerateRSAKeyPair(algo.KeySize2048)
   293  	if err != nil {
   294  		t.Fatalf("Failed to generate RSA key pair: %v", err)
   295  	}
   296  
   297  	data := []byte("test data with metadata")
   298  	opts := encryption.EncryptOptions{
   299  		Algorithm: encryption.AlgorithmRSAOAEP,
   300  		Format:    encryption.FormatCMS,
   301  		Metadata: map[string]interface{}{
   302  			"test_key": "test_value",
   303  			"number":   42,
   304  		},
   305  	}
   306  
   307  	encrypted, err := EncryptWithRSA(data, rsaKeys, opts)
   308  	if err != nil {
   309  		t.Fatalf("Failed to encrypt: %v", err)
   310  	}
   311  
   312  	if encrypted.Metadata == nil {
   313  		t.Error("Metadata should be preserved")
   314  	}
   315  
   316  	if val, ok := encrypted.Metadata["test_key"]; !ok || val != "test_value" {
   317  		t.Error("Metadata not preserved correctly")
   318  	}
   319  
   320  	if val, ok := encrypted.Metadata["number"]; !ok || val != 42 {
   321  		t.Error("Numeric metadata not preserved correctly")
   322  	}
   323  }