How to encrypt files with Ruby and Active Support
In this tutorial, we will create a Ruby binstub that allows you to encrypt and decrypt files using Active Support’s EncryptedFile module. This script is particularly useful for those who need to protect sensitive information within their files.
Use Cases
- Encrypt text files in open source projects so that they can be committed to your repository without exposing sensitive information.
- Storing credentials in an encrypted file, similar to Rails Custom Credentials.
- Taking secure personal notes.
Required Libraries
The script starts with the following lines, which load the required libraries and set up the command line argument handling.
These lines import the necessary Ruby modules: active_support/encrypted_file for encryption and decryption, and securerandom for key generation
Parsing Arguments
The script expects one of three commands as the first argument: setup
,
write
, or read
. If no command is provided, the script will print an error
message and exit.
Helper Methods
The following build_encrypted_file
method creates an instance of
ActiveSupport::EncryptedFile
with the necessary configuration options.
Next, we have two helper methods: handle_missing_key
and
handle_missing_file_argument
. These methods print error messages and exit the
script if a key or a file is missing, respectively.
Executing the Commands
The case
statement is the main part of the script, handling the three possible
commands: write
, read
, and setup
.
Encrypting a File
For the write
command, the script ensures that a file argument is provided
and that a system editor is available to open the file. It then creates a new
encrypted file if it does not exist and opens the file in the system editor for
editing. When the editor is closed, the encrypted file is saved with the new
content.
Decrypting a File
For the read
command, the script ensures that a file argument is provided and
then attempts to read the encrypted file, printing the decrypted contents to the
standard output.
The Setup Script
Finally, the setup
command generates a new encryption key and saves it to a
file named invisible_ink.key
. It also adds the key file to the .gitignore
file to prevent it from being accidentally committed to a version control
system.
The Final Script
By using this script, you can protect sensitive information from unauthorized
access and maintain the privacy of your data. With the setup
, write
, and
read
commands, you can easily manage the encryption and decryption process,
making it a useful tool for various applications.
As an alternative, you can also use the invisible_ink gem, which provides the same functionality as this script, with the added benefit of being easily integrated into any Ruby project. This gem offers a more streamlined and maintainable approach to file encryption and decryption in your Ruby applications, without the need to implement the entire script yourself.