This example demonstrates how to securely handle sensitive (see Security Note) data, such as API keys and passwords, in a Rust application. The setup ensures that sensitive strings are not included in the binary in plaintext and uses encryption to protect secrets during the build process.
- Encryption during Build: The
build.rs
script encrypts thesecrets.toml
file using a predefined key (key
) and saves the result assecrets.toml.encrypted
. - Decryption at Runtime: The main program decrypts the
secrets.toml.encrypted
file at runtime, parses the TOML content, and verifies the data structure. - Static Parsing: The
static_toml
crate provides compile-time validation of the TOML structure. In this experiment, since the same TOML file (though encrypted) is used to build the data structure, deserialization after decryption should not fail unless there is an unexpected issue.
- Place your
secrets.toml
andkey
files in the same directory asmain.rs
andbuild.rs
. - Build the project:
cargo build --release
- Run the application:
You should see:
target/release/example
Nice secrets you got there 😎
To confirm that sensitive strings are not embedded in the binary as plaintext, you can search for them:
strings target/release/example | rg your_api_key_here
This command should return no results, demonstrating that the original secret string is not stored in the binary.
Disclaimer: I am not a security expert, and this experiment is limited in scope. It only checks that the original strings are not visible as plaintext in the binary. This approach does not ensure full security of sensitive data.
Keep in mind:
- A key is still required for encryption and decryption. Managing this securely is crucial.
- Even with obfuscation, a shipped binary can be thoroughly inspected and reverse-engineered.
- It is better to avoid shipping secrets in the binary altogether instead of relying solely on obfuscation.
If you need robust security, consider using secure key management solutions or dedicated libraries designed for handling sensitive data in production environments.