Class: Passr::Encryptor

Inherits:
Object
  • Object
show all
Defined in:
lib/passr/encryptor.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(nonce = nil) ⇒ Encryptor

Returns a new instance of Encryptor.



13
14
15
16
17
# File 'lib/passr/encryptor.rb', line 13

def initialize(nonce = nil)
  @secret_key = load_secret_key || Encryptor.install
  @secret_box = create_secret_box
  @raw_nonce = get_raw_nonce(nonce)
end

Instance Attribute Details

#raw_nonceObject (readonly)

Returns the value of attribute raw_nonce.



11
12
13
# File 'lib/passr/encryptor.rb', line 11

def raw_nonce
  @raw_nonce
end

Class Method Details

.generate_secret_keyObject



19
20
21
22
23
24
25
# File 'lib/passr/encryptor.rb', line 19

def self.generate_secret_key
  key = RbNaCl::Random.random_bytes(RbNaCl::SecretBox.key_bytes)
  File.open(PATH, 'w') do |f|
    f.write "---\nSECRET_KEY: #{Base64.encode64(key)}"
  end
  key
end

.installObject



41
42
43
44
45
46
47
48
49
# File 'lib/passr/encryptor.rb', line 41

def self.install
  unless File.exists? PATH
    FileUtils::mkdir_p File.expand_path('./config/')
    update_gitignore
    generate_secret_key
  else
    raise RuntimeError, "./config/encryptor.yml already exists."
  end
end

.update_gitignoreObject



51
52
53
54
55
56
57
58
# File 'lib/passr/encryptor.rb', line 51

def self.update_gitignore
  gitignore = File.expand_path('./.gitignore')
  unless File.read(gitignore).split("\n").include?('/config/encryptor.yml')
    open(gitignore, 'a') do |f|
      f << "\n# Ignore Passr Encryption Configuration\n/config/encryptor.yml"
    end
  end
end

Instance Method Details

#decrypt(encrypted_password) ⇒ Object



32
33
34
35
# File 'lib/passr/encryptor.rb', line 32

def decrypt(encrypted_password)
  raw_encryption = Base64.decode64(encrypted_password)
  secret_box.decrypt(raw_nonce, raw_encryption)
end

#encrypt(password) ⇒ Object



27
28
29
30
# File 'lib/passr/encryptor.rb', line 27

def encrypt(password)
  raw_encryption = secret_box.encrypt(raw_nonce, password)
  Base64.encode64(raw_encryption).chomp
end

#nonceObject



37
38
39
# File 'lib/passr/encryptor.rb', line 37

def nonce
  Base64.encode64(raw_nonce).chomp
end