Skip to content

Implement genrsa command #2535

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 25 commits into
base: main
Choose a base branch
from
Open

Conversation

kingstjo
Copy link
Contributor

Issues:

Addresses CryptoAlg-3387

Description of changes:

This PR implements the genrsa command for the openssl tool, which generates RSA private keys. This is part of the ongoing effort to implement OpenSSL-compatible CLI tools in AWS-LC.

The implementation includes:

  • Generate RSA private keys with customizable key size
  • Output to file or stdout
  • Proper argument order validation
  • Comprehensive error handling

Call-outs:

N/A

Testing:

  • Added unit tests for basic functionality
  • Added tests for error handling
  • Added cross-compatibility tests with OpenSSL
  • Added parameterized tests for different key sizes (1024, 2048, 3072, 4096)

By submitting this pull request, I confirm that my contribution is made under the terms of the Apache 2.0 license and the ISC license.

kingstjo added 12 commits June 30, 2025 11:24
- Add genrsa.cc with basic option parsing for -out and key size
- Register genrsaTool in kTools array and internal.h
- Update CMakeLists.txt to include genrsa.cc in build
- Implement barebones functionality that outputs detected options
- Support required options: -out <file> and <keysize> (default: 2048)

🤖 Assisted by Amazon Q Developer
- Replace barebones implementation with actual RSA key generation
- Add RSA_generate_key_ex() with RSA_F4 exponent (65537)
- Support key size parsing from positional argument with validation
- Add BIO-based output handling for both stdout and file output
- Include proper error handling for key generation and file operations
- Use bssl::UniquePtr for automatic memory management
- Generate PEM-formatted RSA private keys compatible with OpenSSL

Tested functionality:
- Default 2048-bit key generation to stdout
- Custom key sizes (e.g., 4096-bit)
- File output with -out option
- Input validation and error handling

🤖 Assisted by Amazon Q Developer
- Add genrsa command to tool-openssl with argument parsing
- Enforce OpenSSL-compatible argument order: [options] numbits
- Support -out option and custom key sizes (default: 2048-bit)
- Generate RSA keys in traditional PEM format for broad compatibility
- Add comprehensive test suite with 14 tests covering:
  * Basic functionality (key generation, error handling)
  * Cross-compatibility with OpenSSL (argument order, interoperability)
  * PEM format validation and RSA key component verification
- Use ordered argument parsing to match OpenSSL's strict ordering requirements
- Include environment variable support for CI/CD cross-compatibility testing

Follows AWS-LC CLI tool patterns and PKCS#8 PR feedback on argument order.

🤖 Assisted by Amazon Q Developer
- Replace system() calls with direct genrsaTool() function calls for basic tests
- Add parameterized tests for various key sizes (1024, 2048, 3072, 4096)
- Keep system() calls only for cross-compatibility tests with OpenSSL
- Improve test execution speed by ~10x (no process spawning overhead)
- Add ArgumentOrderValidation test for OpenSSL compatibility
- Maintain all existing functionality while reducing complexity

Performance improvements:
- 19 tests total (was 14): +5 tests with parameterized approach
- 23.1 lines per test (was 24.3): slight improvement in code density
- Direct function calls eliminate process spawning overhead
- Better error reporting with direct stack traces

🤖 Assisted by Amazon Q Developer
…ation and bracing

- Initialize all variables to satisfy cppcoreguidelines-init-variables
- Add braces around single-line if statements per readability-braces-around-statements
- Fix args_list_t, BIGNUM pointer, and primitive variable initialization
- Ensure consistent code style across genrsa.cc, genrsa_test.cc, and tool.cc

All 90 AWS-LC CLI tests now pass with full OpenSSL compatibility.

🤖 Assisted by Amazon Q Developer
…ized testing

- Merge GenRSATest and GenRSAKeySizeTest into single unified class
- Add support for both parameterized and non-parameterized tests in one class
- Fix segmentation fault by using inline checks with explicit returns
- Eliminate code duplication between test classes
- Improve cross-compatibility test coverage for all key sizes (1024, 2048, 3072, 4096)
- Reduce excessive error messages while keeping contextual ones
- Reduce file size from 332 to 300 lines while maintaining full test coverage

🤖 Assisted by Amazon Q Developer
- Add static constants kDefaultKeySize (2048) and kUsageFormat for consistency
- Extract ValidateArgumentOrder() helper function to improve readability
- Extract ParseKeySize() helper function to centralize key size validation
- Reduce main function complexity from ~100 lines to ~55 lines
- Maintain all existing functionality and OpenSSL compatibility
- All 19 genrsa tests continue to pass

This refactoring improves maintainability and makes it easier to modify
validation logic when team feedback is received.

🤖 Assisted by Amazon Q Developer
…exity

- Add ParseArguments helper to centralize argument parsing
- Add GenerateRSAKey helper to encapsulate key generation logic
- Add CreateOutputBIO helper to manage output destination setup
- Add WriteRSAKeyToBIO helper to handle key writing
- Reduce main function complexity from ~55 lines to ~25 lines
- Maintain all existing functionality and OpenSSL compatibility
- All 19 genrsa tests continue to pass

🤖 Assisted by Amazon Q Developer
…nd non-parameterized tests

This change refactors the genrsa_test.cc file to use a hybrid approach:
- Creates a base test fixture with common functionality
- Uses parameterized tests for operations that benefit from testing with different key sizes
- Keeps non-parameterized tests for operations that don't depend on key size
- Reduces test count from 52 to 28 while maintaining comprehensive coverage
- Improves test names and organization for better readability

🤖 Assisted by Amazon Q Developer
- Update DisplayHelp to use BIO for output instead of std::cout
- Add dynamic option lookup with FindOptionByName function
- Fix segmentation faults in tests when environment variables aren't set
- Improve code maintainability for future option additions

🤖 Assisted by Amazon Q Developer
@kingstjo kingstjo requested a review from a team as a code owner July 10, 2025 22:21
Copy link
Contributor

@github-actions github-actions bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

clang-tidy made some suggestions

@codecov-commenter
Copy link

codecov-commenter commented Jul 10, 2025

Codecov Report

Attention: Patch coverage is 78.06452% with 34 lines in your changes missing coverage. Please review.

Please upload report for BASE (main@90fdf5c). Learn more about missing BASE report.

Files with missing lines Patch % Lines
tool-openssl/genrsa_test.cc 67.18% 15 Missing and 6 partials ⚠️
tool-openssl/genrsa.cc 86.66% 12 Missing ⚠️
tool-openssl/tool.cc 0.00% 1 Missing ⚠️
Additional details and impacted files
@@           Coverage Diff           @@
##             main    #2535   +/-   ##
=======================================
  Coverage        ?   78.76%           
=======================================
  Files           ?      647           
  Lines           ?   110786           
  Branches        ?    15670           
=======================================
  Hits            ?    87259           
  Misses          ?    22818           
  Partials        ?      709           

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@kingstjo
Copy link
Contributor Author

See AWS-LC-865 for (aws-lc-ci-integration) build failure

kingstjo added 4 commits July 11, 2025 11:57
This change initializes the bits variable to 0 to address the clang-tidy warning about uninitialized variables.

🤖 Assisted by Amazon Q Developer
…andling

- Added kMinKeySize and kKeyArgName constants
- Updated ParseKeySize to use these constants
- Simplified argument handling by using ordered_args functions

🤖 Assisted by Amazon Q Developer
Use local boolean variable with GetBoolArgument instead of passing nullptr directly
to maintain compatibility with the current implementation.
kingstjo added 8 commits July 17, 2025 10:21
This restores the kTools array size that was incorrectly changed to 12.
The array needs to match the actual number of tool entries.
… handling

- Consolidate key validation into single ValidateKey method
- Add descriptive error messages to assertions
- Improve file handling with ScopedFILE
- Remove redundant test cases
- Clean up code organization and formatting

🤖 Assisted by Amazon Q
…ccess violation

The KeyUniqueness test was opening files twice - once with ScopedFILE and again
inside ReadFileToString. This caused an access violation (0xc0000005) on Windows
in the msys2 ucrt64 CI environment. This change removes the redundant ScopedFILE
handles and directly uses ReadFileToString to avoid the file handle conflict.

🤖 Assisted by Amazon Q Developer
Add a RAII-based cleanup guard to ensure proper BIO flushing and closing
on all exit paths. This approach is more maintainable and scalable as
new features are added to the tool. The guard ensures that file handles
are properly released before the function returns, which is especially
important on Windows where file locking is more restrictive.

This fixes the access violation (0xc0000005) errors in the CI pipeline
when running the GenRSAParamTest.KeyUniqueness test.

🤖 Assisted by Amazon Q Developer
…mpatibility

Use binary mode ("wb") instead of text mode ("w") when opening output files
to ensure proper handling of binary data on Windows platforms. This prevents
line ending conversions and other text-mode processing that can corrupt
binary data in RSA key files.

🤖 Assisted by Amazon Q Developer
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants