Class: Nanite::RsaKeyPair

Inherits:
Object show all
Defined in:
lib/nanite/security/rsa_key_pair.rb

Overview

Allows generating RSA key pairs and extracting public key component Note: Creating a RSA key pair can take a fair amount of time (seconds)

Constant Summary collapse

DEFAULT_LENGTH =
2048

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(length = DEFAULT_LENGTH) ⇒ RsaKeyPair

Create new RSA key pair using ‘length’ bits



13
14
15
# File 'lib/nanite/security/rsa_key_pair.rb', line 13

def initialize(length = DEFAULT_LENGTH)
  @raw_key = OpenSSL::PKey::RSA.generate(length)
end

Instance Attribute Details

#raw_keyObject (readonly)

Underlying OpenSSL keys



10
11
12
# File 'lib/nanite/security/rsa_key_pair.rb', line 10

def raw_key
  @raw_key
end

Class Method Details

.from_data(data) ⇒ Object

Load key pair previously serialized via ‘data’



34
35
36
37
38
# File 'lib/nanite/security/rsa_key_pair.rb', line 34

def self.from_data(data)
  res = RsaKeyPair.allocate
  res.instance_variable_set(:@raw_key, OpenSSL::PKey::RSA.new(data)) 
  res
end

.load(file) ⇒ Object

Load key from file



41
42
43
# File 'lib/nanite/security/rsa_key_pair.rb', line 41

def self.load(file)
  from_data(File.read(file))
end

Instance Method Details

#dataObject Also known as: to_s

Key material in PEM format



28
29
30
# File 'lib/nanite/security/rsa_key_pair.rb', line 28

def data
  raw_key.to_pem
end

#has_private?Boolean

Does key pair include private key?

Returns:

  • (Boolean)


18
19
20
# File 'lib/nanite/security/rsa_key_pair.rb', line 18

def has_private?
  raw_key.private?
end

#save(file) ⇒ Object

Save key to file in PEM format



46
47
48
49
50
# File 'lib/nanite/security/rsa_key_pair.rb', line 46

def save(file)
  File.open(file, "w") do |f|
    f.write(@raw_key.to_pem)
  end
end

#to_publicObject

New RsaKeyPair instance with identical public key but no private key



23
24
25
# File 'lib/nanite/security/rsa_key_pair.rb', line 23

def to_public
  RsaKeyPair.from_data(raw_key.public_key.to_pem)
end