Skip to content

Instantly share code, notes, and snippets.

@releu
Forked from zhum/gist:5865085
Last active December 18, 2015 23:59
Show Gist options
  • Save releu/5865109 to your computer and use it in GitHub Desktop.
Save releu/5865109 to your computer and use it in GitHub Desktop.
Gem::Specification.new do |s|
s.name = 'openssh-key-checker'
s.version = '0.1.0'
s.platform = Gem::Platform::RUBY
s.author = 'Jan Bernacki'
s.email = '[email protected]'
s.summary = 'OpenSSH checker'
s.description = 'OpenSSH checker with system tools'
s.files = ['openssh-key-checker.rb']
s.require_path = '.'
end
require "securerandom"
class OpenSSHKeyChecker
def initialize(key)
@key = key.to_s
end
def valid?
tmpfile = TmpFile.new
tmpfile.write oneliner
system "ssh-keygen -l -f '#{tmpfile.path}' >/dev/null 2>/dev/null"
rescue Invalid
false
ensure
tmpfile.unlink
end
def oneliner
oneliner? ? @key : to_oneliner
end
def oneliner?
@key.lines.size == 1
end
def to_oneliner
tmpfile = TmpFile.new
tmpfile.write @key
oneliner = `ssh-keygen -i -f '#{tmpfile.path}' 2>/dev/null`
$?.success? ? oneliner : raise(Invalid.new)
ensure
tmpfile.unlink
end
class Invalid < StandardError
end
class TmpFile
attr_reader :path
def initialize
@path = "/tmp/openssh-check-#{SecureRandom.hex(8)}"
end
def write(data)
File.open(@path, "wb") { |file| file.write data }
end
def unlink
File.exists?(@path) and File.unlink(@path)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment