Skip to content

Instantly share code, notes, and snippets.

@diasjorge
Last active January 3, 2016 03:39
Show Gist options
  • Save diasjorge/8403392 to your computer and use it in GitHub Desktop.
Save diasjorge/8403392 to your computer and use it in GitHub Desktop.
Small interface to osx keychain using the command security
class Security
attr_reader :app, :service
def initialize(app, service = app)
@app = app
@service = service
end
def get_password
stdout_str, stderr_str, status = Open3.capture3("security find-generic-password -a #{app} -s #{service} -w")
if status.success?
stdout_str.strip
else
nil
end
end
def set_password
password = ask_password
Open3.popen3("security add-generic-password -a #{app} -s #{service} -w #{password}") do |stdin, stdout, stderr, wait_thr|
status = wait_thr.value
if status.success?
password
else
nil
end
end
end
private
def ask_password
password = ask "Enter password: "
if password == ""
raise "Password can't be empty"
end
password_confirmation = ask "Enter password confirmation: "
if password != password_confirmation
raise "Password confirmation does not match"
end
password
rescue => e
puts e.message
retry
end
def ask(message)
print message
system "stty -echo"
password = $stdin.gets
system "stty echo"
puts
(password || "").strip
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment