Class: Imp::EncryptedFile

Inherits:
Object
  • Object
show all
Defined in:
lib/imp/encrypted_file.rb

Overview

Note:

This is NOT a file object. The file’s content is loaded entirely into memory.

A rudimentary wrapper to interface with encrypted files.

Files are saved as a concatination of the password’s salt and a string encrypted with Crypto#encrypt. The string may be marshalled content, or it may be the content itself.

Direct Known Subclasses

EncryptedTree

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(passwd, file, marshal = true) ⇒ EncryptedFile

If the file exists, load the content from it. Otherwise load the content as nil, generate a salt and key to prepare for writing.

Parameters:

  • passwd (String)

    The password.

  • file (String)

    The location of the file.

  • marshal (Boolean) (defaults to: true)

    Whether or not the content is marshalled.



25
26
27
28
29
30
31
32
33
# File 'lib/imp/encrypted_file.rb', line 25

def initialize(passwd, file, marshal = true)
  @file = File.expand_path(file)
  @marshal = marshal
  if File.exists? @file
    init_with_file(passwd)
  else
    first_time_init(passwd)
  end
end

Instance Attribute Details

#contObject

The plaintext content of the encrypted file.



17
18
19
# File 'lib/imp/encrypted_file.rb', line 17

def cont
  @cont
end

Instance Method Details

#closeObject

Nulls the key. (It may still be in memory!)



53
54
55
56
# File 'lib/imp/encrypted_file.rb', line 53

def close
  @cont = nil
  @key  = nil
end

#flushObject

Writes the content to the file.



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/imp/encrypted_file.rb', line 36

def flush
  f = File.new(@file, "w")
  f << @salt
  if @marshal
    cont = Marshal.dump @cont
  else
    cont = @cont
  end
  f << Crypto.encrypt(@key, cont)
  f.flush
  # Encrypted files should only be readable by their owner. Doesn't really
  # add much security but hey.
  f.chmod(0600)
  f.close
end