用ruby读/写密码保护和加密的文件 [英] Reading/Writing password protected and encrypted file in ruby

查看:153
本文介绍了用ruby读/写密码保护和加密的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想加密一个ruby程序将加载数据的文件。
此外,我需要程序提示输入密码,将用于解密该文件。

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.

我已经开始看openpgp,但据我所知,这还是不解决密码问题。

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

推荐答案

有两个简单的方法来做到这一点。一个是shell out to openssl来进行加密/解密。可以说更好的办法是使用 Ruby Crypto gem

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.

加密程序:

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

解密程序:

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

此示例使用Blowfish对称块密码。可以使用其他密封物。此外,您可能希望将固定的字符串连接到密码,以使密钥更长,并帮助将加密/解密绑定到您的应用程序。

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.

这篇关于用ruby读/写密码保护和加密的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆