Skip to content

Instantly share code, notes, and snippets.

@aperia
Created December 8, 2015 19:19
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 aperia/341fae8bc3c5265ea666 to your computer and use it in GitHub Desktop.
Save aperia/341fae8bc3c5265ea666 to your computer and use it in GitHub Desktop.
ruby/openssl
require "openssl"
require "base64"
@algorithm = "AES-256-CBC"
def main(encrypted_data_file, secret_key, decrypted_data_file)
print "Reading encrypted data file... "
encrypted_data = File.open(encrypted_data_file, "r") do |file|
file.read().unpack("m")[0]
end
puts "done."
print "Reading secret key file... "
key = File.open(secret_key, "r") do |file|
file.read().unpack("m")[0]
end
puts "done."
print "Setting up cipher... "
iv = OpenSSL::Cipher::Cipher.new(@algorithm).random_iv
cipher = OpenSSL::Cipher::Cipher.new(@algorithm)
cipher.decrypt
cipher.key = key
cipher.iv = iv
puts "done."
print "Decrypting data... "
decrypted_data = cipher.update(encrypted_data)
decrypted_data << cipher.final
puts "done."
print "Writing decrypted data to file... "
File.open(decrypted_data_file, "w") do |file|
file.write decrypted_data
end
puts "done."
end
abort "usage: decrypt.rb <encrypted-data-file> <secret-key> <decrypted-data-file>" if ARGV.size < 3
main ARGV[0], ARGV[1], ARGV[2]
require "openssl"
require "base64"
@algorithm = "AES-256-CBC"
def main(data_file, secret_key, encrypted_data_file)
print "Reading data file... "
data = File.open(data_file, "r") do |file|
file.read()
end
puts "done."
print "Reading secret key file... "
key = File.open(secret_key, "r") do |file|
file.read().unpack("m")[0]
end
puts "done."
print "Setting up cipher... "
iv = OpenSSL::Cipher::Cipher.new(@algorithm).random_iv
cipher = OpenSSL::Cipher::Cipher.new(@algorithm)
cipher.encrypt
cipher.key = key
cipher.iv = iv
puts "done."
print "Encrypting data... "
encrypted_data = cipher.update(data)
encrypted_data << cipher.final
puts "done."
print "Writing encrypted data to file... "
File.open(encrypted_data_file, "w") do |file|
file.write [encrypted_data].pack("m")
end
puts "done."
end
abort "usage: encrypt.rb <data-file> <secret-key> <encrypted-data-file>" if ARGV.size < 3
main ARGV[0], ARGV[1], ARGV[2]
require "openssl"
require "base64"
@algorithm = "AES-256-CBC"
def main(secret_file)
print "Generating new key... "
key = OpenSSL::Cipher::Cipher.new(@algorithm).random_key
puts "done."
print "Writing key to file '#{secret_file}'... "
File.open(secret_file, "w") do |file|
file.write [key].pack("m")
end
puts "done."
end
abort "usage: key.rb <secret-file>" if ARGV.size < 1
main ARGV[0]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment