views:

498

answers:

1

I want to encrypt a file that a ruby program will be loading data from. In addition, I need the program to prompt for a password on startup that will be used to decrypt the file.

In other words, the file needs to reside encrypted on the machine and only users with passwords will be able to run the app.

I have started to look at openpgp but as far as I understand, this does still not solve the password problem.

+3  A: 

There's two easy ways to go about doing this. One is to shell out to openssl to do your encryption / decryption there. The arguably better way would be to use the Ruby Crypto gem.

Program to encrypt:

require 'rubygems'
require 'crypt/blowfish';

puts "Password? "
pw = gets
puts "Secret data? "
data = gets
blowfish = Crypt::Blowfish.new(pw)
r = StringIO.new(data);
File.open('data', 'w') do |f|
  while l = r.read(8) do
    while l.size < 8 do l += "\0" end
    f.print blowfish.encrypt_block(l)
  end
end

Program to decrypt:

require 'rubygems'
require 'crypt/blowfish';

puts "Password? "
pw = gets
blowfish = Crypt::Blowfish.new(pw)
r = StringIO.new();
File.open('data', 'r') do |f|
  while l = f.read(8) do
    r << blowfish.decrypt_block(l)
  end
end
puts "Secret data:"
puts r.string

This example uses the Blowfish symmetric block cypher. Other cyphers could be used. Also, you would probably want to concatenate a fixed string to the password, to make the key longer and to help tie the encryption/decryption to your application.

brianegge