如何在Rails中解密文件?

时间:2012-12-07 18:33:36

标签: ruby-on-rails aes encryption

哇,我知道这是一个模糊的问题。我的Rails仓库中有一个名为enc_file的文件。

在我的environments/production.rb中,我有:

authentication_file = "#{Rails.root}/enc_file"
unless File.exist?(authentication_file)
    puts "ERROR: File not found! (#{authentication_file})"
    raise SystemExit, 1
end
my_config = YAML.load(PaymentGatewayCipher.decrypt(authentication_file)).symbolize_keys!
config.app_config.pay_pal.merge!(pay_pal_config.slice(:login, :password, :business, :business_id, :cert_id, :private_key, :signature).merge(
  :return_to_merchant => false,
  :server => 'whatever.paypal.com'
))

然后在我的payment_gateway_cipher.rb文件中,我有:

require 'openssl'

# Encapsulates payment gateway encryption / decryption utility functions
class PaymentGatewayCipher
  class << self
    def encrypt(file, options = {})
      cipher = create_cipher
      cipher.encrypt(cipher_key)
      data = cipher.update(File.read(file))
      data << cipher.final

      if to_file = options[:to]
        # Write it out to a different file
        File.open(to_file, 'wb') do |f|
          f << data
        end
      end

      data
    end

    # Decrypts the given file
    def decrypt(file)
      cipher = create_cipher
      cipher.decrypt(cipher_key)
      encrypted_data = File.open(file, 'rb') {|io| io.read}
      data = cipher.update(encrypted_data)
      data << cipher.final
    end

    # Generates the cipher to be used for encryption/decryption
    def create_cipher
      OpenSSL::Cipher::Cipher.new('aes-256-cbc')
    end

    # Loads the cipher key used for the symmetric algorithm
    def cipher_key
      File.open(File.join(Rails.root, 'config/mystuff/live/cipher.key'), 'rb') {|io| io.read}
    end
  end
end

如何解密enc_file以查看Rails之外的内容?我想查看内容,修改它们,并尽可能重新保存文件。

思想?

1 个答案:

答案 0 :(得分:0)

你有decrypt函数就在那里,所以可能是通过输出该函数的结果?

puts decrypt("path/to/enc_file")

或者将其写入一个文件,然后您可以在Ruby之外查看:

File.open("decrypted_file", "w") do |f|
  f.write decrypt("path/to/enc_file")
end