Read / write password protected and encrypted file in ruby

I want to encrypt the file from which the ruby ​​program will be loaded. In addition, I need a program to request a password at startup, which will be used to decrypt the file.

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

I started looking at openpgp, but as I understand it, this still does not solve the password problem.

+3
source share
2 answers

There are two easy ways to do this. One of them is to put it on openssl to perform encryption / decryption there. Perhaps the best way would be to use a Ruby Crypto gem .

Program for encryption:

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 for decryption:

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 cipher. Other ciphers may be used. In addition, you probably want to combine a fixed string with a password to make the key longer and help to associate encryption / decryption with your application.

+6
source

Try an encrypted string stone . It works like a charm.

0
source

Source: https://habr.com/ru/post/1712212/


All Articles