Skip to content

Instantly share code, notes, and snippets.

@mldoscar
Created December 8, 2021 21:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mldoscar/ede289118cdb9106a8e5227a05bdc9f7 to your computer and use it in GitHub Desktop.
Save mldoscar/ede289118cdb9106a8e5227a05bdc9f7 to your computer and use it in GitHub Desktop.
gpg utility for encrypting and decrypting files
# encoding: utf-8
require 'io/console'
require 'optparse'
def show_wait_spinner(fps=10)
chars = %w[| / - \\]
delay = 1.0/fps
iter = 0
spinner = Thread.new do
while iter do # Keep spinning until told otherwise
print chars[(iter+=1) % chars.length]
sleep delay
print "\b"
end
end
yield.tap{ # After yielding to the block, save the return value
iter = false # Tell the thread to exit, cleaning up after itself…
spinner.join # …and wait for it to do so.
} # Use the block's return value as the method's
end
opts = {}
OptionParser.new do |opt|
opt.on('-e', '--encrypt [file]', 'Encrypt the given file') { |o| opts[:encrypt] = true; opts[:file] = o; }
opt.on('-d', '--decrypt [file]', 'Decrypt the given file') { |o| opts[:encrypt] = false; opts[:file] = o; }
opt.on('-o', '--output [file]', 'Specify the output of the encrypted/decrypted file') { |o| opts[:output] = o }
end.parse!
# Check mandatory values
unless (opts.keys.length == 3)
raise Exception.new('Not enough options to execute this script were given. Try to run this script with [-h || --help] argument to learn more.')
end
# Check gpg command exists
if `which gpg`.chomp.length.zero?
raise Exception.new("gpg utility is not installed.")
end
# Check file exists
unless File.exists?(opts[:file])
raise Exception.new("Input file '#{opts[:file]}' does not exists.")
end
# Check output does not exists
if File.exists?(opts[:output])
raise Exception.new("Output file '#{opts[:output]}' already exists.")
end
if opts[:encrypt]
puts 'Enter the password to encrypt the file: '
password = STDIN.noecho(&:gets).chomp
show_wait_spinner do
`gpg --yes --batch --passphrase=\"#{password}\" --output #{opts[:output]} -c #{opts[:file]}`
end
else
puts 'Enter the password to decrypt the file: '
password = STDIN.noecho(&:gets).chomp
show_wait_spinner do
`gpg --yes --batch --passphrase=\"#{password}\" --output #{opts[:output]} -d #{opts[:file]}`
end
end
puts "**** DONE! ****"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment