Created
October 18, 2011 15:57
-
-
Save benmanns/1295804 to your computer and use it in GitHub Desktop.
Provides symmetric encryption from abc.txt to abc.encrypted and abc.encrypted to abc.txt.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# See http://ruby-doc.org/stdlib-1.9.2/libdoc/digest/rdoc/Digest/Class.html#method-c-digest | |
# See http://ruby-doc.org/stdlib-1.9.2/libdoc/openssl/rdoc/OpenSSL/Cipher.html | |
# See http://ruby.about.com/od/rubyfeatures/a/argv.htm | |
require 'openssl' | |
# Use this section to encrypt a file | |
input_file = 'abc.txt' | |
output_file = 'abc.encrypted' | |
encryption_key = 'secret password' | |
encryption_key = Digest::SHA256.digest(encryption_key) # Hash the password to make a 256 bit key | |
# Set up AES | |
cipher = OpenSSL::Cipher::Cipher.new('aes-256-cbc') | |
cipher.encrypt | |
cipher.key = encryption_key | |
cipher.iv = iv = cipher.random_iv # Save the IV so that we can store it in the file | |
# Open the encryption output file | |
File.open output_file, 'w' do |output| | |
output << iv # Store the IV | |
# Open the input file | |
File.open input_file do |input| | |
while text = input.read(256) | |
output << cipher.update(text) # Output the block of encrypted data | |
end | |
end | |
output << cipher.final # Output the end of encrypted data | |
end | |
# Use this section to decrypt a file | |
input_file = 'abc.encrypted' | |
output_file = 'abc.txt' | |
encryption_key = 'secret password' | |
encryption_key = Digest::SHA256.digest(encryption_key) # Hash the password to make a 256 bit key | |
# Set up AES | |
cipher = OpenSSL::Cipher::Cipher.new('aes-256-cbc') | |
cipher.decrypt | |
cipher.key = encryption_key | |
# Open the output file | |
File.open output_file, 'w' do |output| | |
# Open the encrypted input file | |
File.open input_file do |input| | |
cipher.iv = input.read(cipher.iv_len) # Load the IV from the file | |
while text = input.read(256) | |
output << cipher.update(text) # Output the block of decrypted data | |
end | |
output << cipher.final # Output the end of decrypted data | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment