summaryrefslogtreecommitdiff
path: root/lib/leap_cli/util
diff options
context:
space:
mode:
authorelijah <elijah@riseup.net>2016-06-29 16:55:06 -0700
committerelijah <elijah@riseup.net>2016-07-01 14:48:42 -0700
commit5780f5dcc024d4f140fe8f6e8dc3f7c4e905a8ec (patch)
treed68e366f74129f0fcad06fc415f9ab0e65ead50f /lib/leap_cli/util
parente03bfce9db2a213527beb16a4f4dd1f13d96be6e (diff)
leap cli: move everything we can from leap_cli to leap_platform
Diffstat (limited to 'lib/leap_cli/util')
-rw-r--r--lib/leap_cli/util/secret.rb55
-rw-r--r--lib/leap_cli/util/x509.rb33
2 files changed, 88 insertions, 0 deletions
diff --git a/lib/leap_cli/util/secret.rb b/lib/leap_cli/util/secret.rb
new file mode 100644
index 00000000..749b9595
--- /dev/null
+++ b/lib/leap_cli/util/secret.rb
@@ -0,0 +1,55 @@
+# encoding: utf-8
+#
+# A simple secret generator
+#
+# Uses OpenSSL random number generator instead of Ruby's rand function
+#
+autoload :OpenSSL, 'openssl'
+
+module LeapCli; module Util
+ class Secret
+ CHARS = (('A'..'Z').to_a + ('a'..'z').to_a + ('0'..'9').to_a) - "i1loO06G".split(//u)
+ HEX = (0..9).to_a + ('a'..'f').to_a
+
+ #
+ # generate a secret with with no ambiguous characters.
+ #
+ # +length+ is in chars
+ #
+ # Only alphanumerics are allowed, in order to make these passwords work
+ # for REST url calls and to allow you to easily copy and paste them.
+ #
+ def self.generate(length = 16)
+ seed
+ OpenSSL::Random.random_bytes(length).bytes.to_a.collect { |byte|
+ CHARS[ byte % CHARS.length ]
+ }.join
+ end
+
+ #
+ # generates a hex secret, instead of an alphanumeric on.
+ #
+ # length is in bits
+ #
+ def self.generate_hex(length = 128)
+ seed
+ OpenSSL::Random.random_bytes(length/4).bytes.to_a.collect { |byte|
+ HEX[ byte % HEX.length ]
+ }.join
+ end
+
+ private
+
+ def self.seed
+ @pid ||= 0
+ pid = $$
+ if @pid != pid
+ now = Time.now
+ ary = [now.to_i, now.nsec, @pid, pid]
+ OpenSSL::Random.seed(ary.to_s)
+ @pid = pid
+ end
+ end
+
+ end
+end; end
diff --git a/lib/leap_cli/util/x509.rb b/lib/leap_cli/util/x509.rb
new file mode 100644
index 00000000..787fdfac
--- /dev/null
+++ b/lib/leap_cli/util/x509.rb
@@ -0,0 +1,33 @@
+autoload :OpenSSL, 'openssl'
+autoload :CertificateAuthority, 'certificate_authority'
+
+require 'digest'
+require 'digest/md5'
+require 'digest/sha1'
+
+module LeapCli; module X509
+ extend self
+
+ #
+ # returns a fingerprint of a x509 certificate
+ #
+ def fingerprint(digest, cert_file)
+ if cert_file.is_a? String
+ cert = OpenSSL::X509::Certificate.new(Util.read_file!(cert_file))
+ elsif cert_file.is_a? OpenSSL::X509::Certificate
+ cert = cert_file
+ elsif cert_file.is_a? CertificateAuthority::Certificate
+ cert = cert_file.openssl_body
+ end
+ digester = case digest
+ when "MD5" then Digest::MD5.new
+ when "SHA1" then Digest::SHA1.new
+ when "SHA256" then Digest::SHA256.new
+ when "SHA384" then Digest::SHA384.new
+ when "SHA512" then Digest::SHA512.new
+ end
+ digester.hexdigest(cert.to_der)
+ end
+
+
+end; end