Class: Encryptatron::FileHandler
- Inherits:
-
Object
- Object
- Encryptatron::FileHandler
- Defined in:
- lib/encryptatron/file.rb
Instance Attribute Summary collapse
-
#data ⇒ Object
Returns the value of attribute data.
-
#enc_file ⇒ Object
Returns the value of attribute enc_file.
-
#file ⇒ Object
Returns the value of attribute file.
-
#iv_file ⇒ Object
Returns the value of attribute iv_file.
Instance Method Summary collapse
- #encrypt!(encoded_key = nil) ⇒ Object
-
#initialize(file) ⇒ FileHandler
constructor
A new instance of FileHandler.
- #load(key) ⇒ Object
- #load_encrypted(encoded_key) ⇒ Object
- #load_unencrypted ⇒ Object
Constructor Details
#initialize(file) ⇒ FileHandler
Returns a new instance of FileHandler.
12 13 14 |
# File 'lib/encryptatron/file.rb', line 12 def initialize(file) self.file = file end |
Instance Attribute Details
#data ⇒ Object
Returns the value of attribute data.
9 10 11 |
# File 'lib/encryptatron/file.rb', line 9 def data @data end |
#enc_file ⇒ Object
Returns the value of attribute enc_file.
9 10 11 |
# File 'lib/encryptatron/file.rb', line 9 def enc_file @enc_file end |
#file ⇒ Object
Returns the value of attribute file.
10 11 12 |
# File 'lib/encryptatron/file.rb', line 10 def file @file end |
#iv_file ⇒ Object
Returns the value of attribute iv_file.
9 10 11 |
# File 'lib/encryptatron/file.rb', line 9 def iv_file @iv_file end |
Instance Method Details
#encrypt!(encoded_key = nil) ⇒ Object
45 46 47 48 49 50 51 52 53 54 55 56 57 |
# File 'lib/encryptatron/file.rb', line 45 def encrypt!(encoded_key = nil) cipher = OpenSSL::Cipher::AES.new(256, :CBC) cipher.encrypt key = encoded_key.nil? ? cipher.random_key : Base64.decode64(encoded_key) cipher.key = key iv = cipher.random_iv encrypted = cipher.update(data.to_json) + cipher.final File.write(enc_file, encrypted) File.write(iv_file, iv) Base64.encode64(key) end |
#load(key) ⇒ Object
22 23 24 25 26 |
# File 'lib/encryptatron/file.rb', line 22 def load(key) self.data = File.exist?(file) ? load_unencrypted : {} data.deep_merge!(load_encrypted(key)) if File.exist?(enc_file) && File.exist?(iv_file) data end |
#load_encrypted(encoded_key) ⇒ Object
32 33 34 35 36 37 38 39 40 41 42 43 |
# File 'lib/encryptatron/file.rb', line 32 def load_encrypted(encoded_key) raise 'Encryption key is nil, you may need to set the ENCRYPTATRON_KEY environment variable' unless encoded_key key = Base64.decode64(encoded_key) decipher = OpenSSL::Cipher::AES.new(256, :CBC) decipher.decrypt decipher.iv = File.read(iv_file) decipher.key = key encrypted = File.read(enc_file) plain = decipher.update(encrypted) + decipher.final self.data = JSON.parse(plain) end |
#load_unencrypted ⇒ Object
28 29 30 |
# File 'lib/encryptatron/file.rb', line 28 def load_unencrypted self.data = YAML.load_file(file) if File.exist?(file) end |