-
-
Save releu/5865109 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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