简体   繁体   中英

Ruby: How to decrypt *.csv.gpg file using public/private key

I have a requirement to decrypt a .csv.pgp file that should be decrypted by using the public / private key, shared in public.

I tried to find some resources https://github.com/rocketjob/rocketjob/wiki/PGP-Encryption-with-Ruby Ruby: file encryption/decryption with private/public keys But did not work out.

Thanks in advance!

Assuming you have a Gemfile like:

source 'https://rubygems.org'

gem 'iostreams', '~> 0.14.0'

The following script will prompt you for the receiver's key ID and passphrase

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 '--------------'

The bit you may have been missing is calling out to download ("receive") the key from the public server for the recipient.

Thanks to the RocketJob docs for some of the legwork here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM