Ruby:如何使用公钥/私钥解密* .csv.gpg文件

时间:2018-02-21 09:06:16

标签: ruby encryption

我要求解密应该使用公共共享的公钥/私钥解密的* .csv.pgp文件。

我试图找到一些资源 https://github.com/rocketjob/rocketjob/wiki/PGP-Encryption-with-Ruby Ruby: file encryption/decryption with private/public keys 但没有成功。

提前致谢!

1 个答案:

答案 0 :(得分:2)

假设你有Gemfile喜欢:

source 'https://rubygems.org'

gem 'iostreams', '~> 0.14.0'

以下脚本将提示您输入接收者的密钥ID和密码

require 'rubygems'
require 'bundler/setup'
require 'io/console'

require 'iostreams'

csv_filename = './data.csv'
encrypted_filename = './secure.pgp'
csv_data = File.read(csv_filename)

puts "Generating sender's key..."
signer_passphrase = 'somethingreallysecure'
sender_key_id = IOStreams::Pgp.generate_key(
  name:       'Sender',
  email:      'sender@example.org',
  passphrase: signer_passphrase
)

puts 'Enter receiver key ID:'
receiver_key_id = gets.strip

puts "Downloading receiver's key..."
puts `gpg --keyserver keyserver.ubuntu.com --recv #{receiver_key_id}`

puts "Encrypting #{csv_filename} to #{encrypted_filename}"
sender_key = IOStreams::Pgp.list_keys(key_id: sender_key_id).first
receiver_key = IOStreams::Pgp.list_keys(key_id: receiver_key_id).first

IOStreams::Pgp::Writer.open(
  'secure.pgp',
  recipient:         receiver_key[:email],
  signer:            sender_key[:email],
  signer_passphrase: signer_passphrase
) do |output|
  output.puts(csv_data)
end

puts "Decrypting #{encrypted_filename}"
puts 'Enter receiver passphrase:'
receiver_passphrase = STDIN.noecho(&:gets).chomp
decrypted_data = ''
IOStreams::Pgp::Reader.open('secure.pgp', passphrase: receiver_passphrase) do |stream|
  decrypted_data += stream.read(10) until stream.eof?
end

puts ''
puts 'Source data'
puts '--------------'
puts csv_data
puts '--------------'
puts ''
puts 'Decrypted data'
puts '--------------'
puts decrypted_data
puts '--------------'

您可能缺少的一点是呼叫从公共服务器下载(“接收”)密钥给收件人。

感谢RocketJob docs对于这里的一些法律工作。