Class: Credstore::Crypt

Inherits:
Object
  • Object
show all
Defined in:
lib/credstore/crypt.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(opts = {}) ⇒ Crypt

Returns a new instance of Crypt.



16
17
18
19
20
21
22
23
24
25
26
# File 'lib/credstore/crypt.rb', line 16

def initialize(opts={})
  opts[:keys_dir] ||= "./"
  opts[:public_key] ||= "id_rsa.pub"
  @data_path = opts[:keys_dir]
  @public_path = File.join(@data_path, opts[:public_key])
  @public = get_key opts[:public_key]
  if opts[:private_key]
    @private_path = File.join(@data_path, opts[:private_key])
    @private = get_key opts[:private_key]
  end
end

Class Method Details

.generate_keys(opts = {:length=>2048, :keys_dir=>"#{$LIB_BASE_DIR}/tmp/", :public_key=>"id_rsa.pub", :private_key=>"id_rsa"}) ⇒ Object



39
40
41
42
43
44
45
46
# File 'lib/credstore/crypt.rb', line 39

def self.generate_keys(opts={:length=>2048, :keys_dir=>"#{$LIB_BASE_DIR}/tmp/", :public_key=>"id_rsa.pub", :private_key=>"id_rsa"})
  unless File.exists?(File.join(opts[:keys_dir], opts[:private_key])) || File.exists?(File.join(opts[:keys_dir], opts[:public_key]))
    keypair  = OpenSSL::PKey::RSA.generate(opts[:length])
    Dir.mkdir(opts[:keys_dir]) unless File.exist?(opts[:keys_dir])
    File.open(File.join(opts[:keys_dir], opts[:private_key]), 'w') { |f| f.write keypair.to_pem } unless File.exists? File.join(opts[:keys_dir], opts[:private_key])
    File.open(File.join(opts[:keys_dir], opts[:public_key]), 'w') { |f| f.write keypair.public_key.to_pem } unless File.exists? File.join(opts[:keys_dir], opts[:public_key])
  end
end

Instance Method Details

#decrypt_string(message) ⇒ Object



32
33
34
35
36
37
# File 'lib/credstore/crypt.rb', line 32

def decrypt_string message
  if message.nil?
    return nil
  end
  @private.private_decrypt Base64::decode64(message)
end

#encrypt_string(message) ⇒ Object



28
29
30
# File 'lib/credstore/crypt.rb', line 28

def encrypt_string message
  Base64::encode64(@public.public_encrypt(message)).rstrip
end