Module: DevCert::Util

Defined in:
lib/devcert/util.rb

Class Method Summary collapse

Class Method Details

.export(path, entity) ⇒ Object



42
43
44
45
46
# File 'lib/devcert/util.rb', line 42

def self.export(path, entity)
  open path, 'w' do |io|
    io.write(entity.to_pem)
  end
end

.generate_ec_key(size) ⇒ Object



74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# File 'lib/devcert/util.rb', line 74

def self.generate_ec_key(size)
  curve_name = nil
  if size == 256
    curve_name = 'prime256v1'
  elsif curve_name == 384
    curve_name = 'secp384r1'
  end

  raise 'Unsupported curve!' if curve_name.nil?

  private_key = ::OpenSSL::PKey::EC.new(curve_name)
  public_key = ::OpenSSL::PKey::EC.new(curve_name)

  private_key.generate_key
  public_key.public_key = private_key.public_key
  return private_key, public_key
end

.generate_rsa_key(size) ⇒ Object



69
70
71
72
# File 'lib/devcert/util.rb', line 69

def self.generate_rsa_key(size)
  key = ::OpenSSL::PKey::RSA.new(size)
  return key, key.public_key
end

.generate_serialObject



62
63
64
65
66
67
# File 'lib/devcert/util.rb', line 62

def self.generate_serial
  machine_bytes = ['foo'].pack('p').size
  machine_bits = machine_bytes * 8
  machine_max_signed = 2**(machine_bits - 1) - 1
  ::SecureRandom.random_number(machine_max_signed)
end

.get_defaultsObject



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/devcert/util.rb', line 9

def self.get_defaults
  path = ::File.absolute_path('defaults.yaml', ::Dir.pwd)
  data = \
    if ::File.exist?(path)
      ::YAML.load(::File.open(path)).fetch('devcert', {})
    else
      {}
    end

  {
    organization: data.fetch('organization', 'Acme Ltd.'),
    country: data.fetch('country', 'US'),
    state_name: data.fetch('state_name', 'California'),
    locality: data.fetch('locality', 'San Francisco')
  }
end

.load_bundle(path) ⇒ Object



48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/devcert/util.rb', line 48

def self.load_bundle(path)
  full_path = ::File.absolute_path(path, __dir__)
  if ::File.exist?(full_path)
    data = ::YAML.load(::File.open(full_path))
    {
      common_name: data[:common_name],
      private_key: ::OpenSSL::PKey.read(data[:private_key]),
      certificate: ::OpenSSL::X509::Certificate.new(data[:certificate])
    }
  else
    raise "No bundle at #{full_path} exists!"
  end
end

.normalize_name(name) ⇒ Object



26
27
28
# File 'lib/devcert/util.rb', line 26

def self.normalize_name(name)
  name.gsub(/[ .-]/, '_')
end

.save_bundle(path, common_name, key, cert) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
# File 'lib/devcert/util.rb', line 30

def self.save_bundle(path, common_name, key, cert)
  bundle = {
    common_name: common_name,
    private_key: key.to_der,
    certificate: cert.to_der
  }

  open path, 'w' do |io|
    io.write(bundle.to_yaml)
  end
end