class Hkp

simple HKP client for public key search and retrieval

Public Class Methods

new(options = {}) click to toggle source
# File lib/hkp.rb, line 64
def initialize(options = {})
  if String === options
    options = { keyserver: options }
  end
  @keyserver = options.delete(:keyserver) || lookup_keyserver || 'http://pool.sks-keyservers.net:11371'
  @options = { raise_errors: true }.merge options
end

Public Instance Methods

fetch(id) click to toggle source

returns the key data as returned from the server as a string

# File lib/hkp.rb, line 103
def fetch(id)
  result = hkp_client.get "/pks/lookup?options=mr&op=get&search=0x#{URI.escape id}"
  return clean_key(result) if result

rescue Exception
  raise $! if raise_errors?
  nil
end
fetch_and_import(id) click to toggle source

fetches key data by id and imports the found key(s) into GPG, returning the full hex fingerprints of the imported key(s) as an array. Given there are no collisions with the id given / the server has returned exactly one key this will be a one element array.

# File lib/hkp.rb, line 116
def fetch_and_import(id)
  if key = fetch(id)
    GPGME::Key.import(key).imports.map(&:fpr)
  end
rescue Exception
  raise $! if raise_errors?
end
raise_errors?() click to toggle source
# File lib/hkp.rb, line 72
def raise_errors?
  !!@options[:raise_errors]
end

Private Instance Methods

clean_key(key) click to toggle source
# File lib/hkp.rb, line 130
def clean_key(key)
  if key =~ /(-----BEGIN PGP PUBLIC KEY BLOCK-----.*-----END PGP PUBLIC KEY BLOCK-----)/m
    return $1
  end
end
exec_cmd(cmd) click to toggle source
# File lib/hkp.rb, line 136
def exec_cmd(cmd)
  res = `#{cmd}`
  return nil if $?.exitstatus != 0
  res
end
hkp_client() click to toggle source
# File lib/hkp.rb, line 126
def hkp_client
  @hkp_client ||= Client.new @keyserver, ssl_verify_mode: @options[:ssl_verify_mode]
end
lookup_keyserver() click to toggle source
# File lib/hkp.rb, line 142
def lookup_keyserver
  url = nil
  if res = exec_cmd("gpgconf --list-options gpgs 2>&1 | grep keyserver 2>&1")
    url = URI.decode(res.split(":").last.split("\"").last.strip)
  elsif res = exec_cmd("gpg --gpgconf-list 2>&1 | grep gpgconf-gpg.conf 2>&1")
    conf_file = res.split(":").last.split("\"").last.strip
    if res = exec_cmd("cat #{conf_file} 2>&1 | grep ^keyserver 2>&1")
      url = res.split(" ").last.strip
    end
  end
  url =~ /^(http|hkp)/ ? url : nil
end