class Zold::Key

A key

Constants

ROOT

Public key of the root wallet

Public Class Methods

new(file: nil, text: nil) click to toggle source
# File lib/zold/key.rb, line 35
def initialize(file: nil, text: nil)
  @body = lambda do
    unless file.nil?
      path = File.expand_path(file)
      raise "Can't find RSA key at #{file} (#{path})" unless File.exist?(path)
      return IO.read(path)
    end
    unless text.nil?
      return text if text.start_with?('-----')
      return [
        '-----BEGIN PUBLIC KEY-----',
        text.gsub(/(?<=\G.{64})/, "\n"),
        '-----END PUBLIC KEY-----'
      ].join("\n")
    end
    raise 'Either file or text must be set'
  end
end

Public Instance Methods

==(other) click to toggle source
# File lib/zold/key.rb, line 61
def ==(other)
  to_s == other.to_s
end
root?() click to toggle source
# File lib/zold/key.rb, line 57
def root?
  to_s == ROOT.to_s
end
sign(text) click to toggle source
# File lib/zold/key.rb, line 73
def sign(text)
  Base64.encode64(rsa.sign(OpenSSL::Digest::SHA256.new, text)).delete("\n")
end
to_pub() click to toggle source
# File lib/zold/key.rb, line 69
def to_pub
  to_s.delete("\n").gsub(/-{5}[ A-Z]+-{5}/, '')
end
to_s() click to toggle source
# File lib/zold/key.rb, line 65
def to_s
  rsa.to_s.strip
end
verify(signature, text) click to toggle source
# File lib/zold/key.rb, line 77
def verify(signature, text)
  rsa.verify(OpenSSL::Digest::SHA256.new, Base64.decode64(signature), text)
end

Private Instance Methods

rsa() click to toggle source
# File lib/zold/key.rb, line 83
def rsa
  text = @body.call.strip
  unless text.start_with?('-----BEGIN')
    Tempfile.open do |f|
      IO.write(f.path, text)
      text = `ssh-keygen -f #{f.path} -e -m pem`
    end
  end
  begin
    OpenSSL::PKey::RSA.new(text)
  rescue OpenSSL::PKey::RSAError => e
    raise "Can't read RSA key (#{e.message}): #{text}"
  end
end