Class: Scl::RSA

Inherits:
Object
  • Object
show all
Defined in:
lib/scl/rsa.rb

Defined Under Namespace

Classes: Key

Constant Summary collapse

DELIMITER =
"\x0::\x0"

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(file: nil, public: nil, private: nil, input_encoder: Format::BINARY, output_encoder: Format::BINARY) ⇒ RSA

Returns a new instance of RSA.



6
7
8
9
10
11
12
13
14
15
16
17
# File 'lib/scl/rsa.rb', line 6

def initialize(file: nil, public: nil, private: nil, input_encoder: Format::BINARY, output_encoder: Format::BINARY)
  if file
    @public  = OpenSSL::PKey::RSA.new(encoder.decode(IO.read("#{file}.pub"))) if File.exists?("#{file}.pub")
    @private = OpenSSL::PKey::RSA.new(encoder.decode(IO.read("#{file}.priv"))) if File.exists?("#{file}.priv")
  else
    @public  = public
    @private = private
  end
  @output_encoder = output_encoder
  @public  = Key.new(@public)
  @private = Key.new(@private)
end

Instance Attribute Details

#privateObject (readonly)

Returns the value of attribute private.



3
4
5
# File 'lib/scl/rsa.rb', line 3

def private
  @private
end

#publicObject (readonly)

Returns the value of attribute public.



3
4
5
# File 'lib/scl/rsa.rb', line 3

def public
  @public
end

Class Method Details

.encrypt(msg, key_size = 1024) ⇒ Object



30
31
32
33
# File 'lib/scl/rsa.rb', line 30

def self.encrypt(msg, key_size=1024)
  pair = self.generate(key_size)
  [pair.private.export, pair.public.export, pair.private.encrypt(msg)]
end

.generate(key_size = 1024) ⇒ Object



25
26
27
28
# File 'lib/scl/rsa.rb', line 25

def self.generate(key_size=1024)
  rsa_pair = OpenSSL::PKey::RSA.new(key_size || 2048)
  RSA.new(public: rsa_pair.public_key, private: rsa_pair)
end

Instance Method Details

#save(dir, name = 'rsa-keypair') ⇒ Object



19
20
21
22
23
# File 'lib/scl/rsa.rb', line 19

def save(dir, name='rsa-keypair')
  IO.write(File.join(dir, "#{name}.pub"),  @output_encoder.encode(@public.export))
  IO.write(File.join(dir, "#{name}.priv"), @output_encoder.encode(@private.export))
  dir
end