Skip to content

Instantly share code, notes, and snippets.

@cboin
Created June 27, 2017 08:57
Show Gist options
  • Save cboin/f70503e4cfc33d303da74d1859bc4f70 to your computer and use it in GitHub Desktop.
Save cboin/f70503e4cfc33d303da74d1859bc4f70 to your computer and use it in GitHub Desktop.
Encrypt/Decrypt File with AES in Ruby
require 'yaml'
require 'openssl'
def read_config
unless File.exist?(ENV["HOME"] + "/.mabs_api.yml")
key = {
:key => cipher.random_key,
:iv => cipher.random_iv
}
File.write(ENV["HOME"] + "/.mabs_api.yml", key.to_yaml)
end
YAML.load_file(ENV["HOME"] + "/.mabs_api.yml")
end
# Used as flag to whether to encrypt or decrypt the file
# By default we encrypt the files
fdecrypt = false
aes = OpenSSL::Cipher::AES.new(128, :CBC)
if ARGV.empty? || ARGV[0] == "--help"
abort "Use --encrypt/--decrypt to encrypt/decrypt the given file"
end
case ARGV[0]
when "--encrypt"
aes.encrypt
when "--decrypt"
aes.decrypt
fdecrypt = true
else
abort "Unknow arguments #{ARGV[0]}"
end
config = read_config
aes.key = config[:key]
aes.iv = config[:iv]
content = File.read(ARGV[1])
if fdecrypt
filename = ARGV[1].chomp(".enc")
final_content = aes.update(content) + aes.final
else
filename = ARGV[1] + ".enc"
final_content = aes.update(content) + aes.final
end
File.write(filename, final_content)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment