Class: IOStreams::Pgp::Reader

Inherits:
Reader
  • Object
show all
Defined in:
lib/io_streams/pgp/reader.rb

Class Attribute Summary collapse

Attributes inherited from Reader

#input_stream

Class Method Summary collapse

Methods inherited from Reader

#initialize, open, stream

Constructor Details

This class inherits a constructor from IOStreams::Reader

Class Attribute Details

.default_passphrase=(value) ⇒ Object

Sets the attribute default_passphrase

Parameters:

  • value

    the value to set the attribute default_passphrase to.



8
9
10
# File 'lib/io_streams/pgp/reader.rb', line 8

def default_passphrase=(value)
  @default_passphrase = value
end

Class Method Details

.file(file_name, passphrase: nil) ⇒ Object

Read from a PGP / GPG file , decompressing the contents as it is read.

file_name: [String]

Name of file to read from

passphrase: [String]

Pass phrase for private key to decrypt the file with

Raises:

  • (ArgumentError)


24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/io_streams/pgp/reader.rb', line 24

def self.file(file_name, passphrase: nil)
  # Cannot use `passphrase: self.default_passphrase` since it is considered private
  passphrase ||= default_passphrase
  raise(ArgumentError, "Missing both passphrase and IOStreams::Pgp::Reader.default_passphrase") unless passphrase

  loopback = IOStreams::Pgp.pgp_version.to_f >= 2.1 ? "--pinentry-mode loopback" : ""
  command  = "#{IOStreams::Pgp.executable} #{loopback} --batch --no-tty --yes --decrypt --passphrase-fd 0 #{file_name}"
  IOStreams::Pgp.logger&.debug { "IOStreams::Pgp::Reader.open: #{command}" }

  # Read decrypted contents from stdout
  Open3.popen3(command) do |stdin, stdout, stderr, waith_thr|
    stdin.puts(passphrase) if passphrase
    stdin.close
    result =
      begin
        stdout.binmode
        yield(stdout)
      rescue Errno::EPIPE
        # Ignore broken pipe because gpg terminates early due to an error
        raise(Pgp::Failure, "GPG Failed reading from encrypted file: #{file_name}: #{stderr.read.chomp}")
      end
    raise(Pgp::Failure, "GPG Failed to decrypt file: #{file_name}: #{stderr.read.chomp}") unless waith_thr.value.success?

    result
  end
end