Class: Encrypth::WebArchiver

Inherits:
Object
  • Object
show all
Defined in:
lib/encrypth/web_archiver.rb

Constant Summary collapse

SALT_LEN =
32
IV_LEN =
12
TAG_LEN =
16

Instance Method Summary collapse

Constructor Details

#initialize(password) ⇒ WebArchiver

Returns a new instance of WebArchiver.



7
8
9
# File 'lib/encrypth/web_archiver.rb', line 7

def initialize(password)
  @password = password
end

Instance Method Details

#decrypt(archive_path, destination) ⇒ Object



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/encrypth/web_archiver.rb', line 46

def decrypt(archive_path, destination)
  File.open(archive_path, 'rb') do |file|
    salt = file.read(SALT_LEN)
    iv   = file.read(IV_LEN)
    
    ciphertext_len = File.size(archive_path) - SALT_LEN - IV_LEN - TAG_LEN
    key = derive_key(@password, salt)
    
    cipher = OpenSSL::Cipher.new('aes-256-gcm').decrypt
    cipher.key = key
    cipher.iv = iv
    
    ciphertext = file.read(ciphertext_len)
    auth_tag = file.read(TAG_LEN)
    cipher.auth_tag = auth_tag
    
    decrypted_data = cipher.update(ciphertext) + cipher.final
    
    tar_path = File.join(Dir.tmpdir, "dec_#{SecureRandom.hex(8)}.tar")
    File.binwrite(tar_path, decrypted_data)
    
    begin
      extract_tar(tar_path, destination)
    ensure
      File.delete(tar_path) if File.exist?(tar_path)
    end
  end
end

#encrypt(files) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/encrypth/web_archiver.rb', line 11

def encrypt(files)
  out_path = File.join(Dir.tmpdir, "enc_#{SecureRandom.hex(8)}.tar.enc")
  tar_path = File.join(Dir.tmpdir, "tar_#{SecureRandom.hex(8)}.tar")
  
  salt = OpenSSL::Random.random_bytes(SALT_LEN)
  key = derive_key(@password, salt)
  
  begin
    create_tar(files, tar_path)
    
    cipher = OpenSSL::Cipher.new('aes-256-gcm').encrypt
    cipher.key = key
    iv = cipher.random_iv
    cipher.iv_len = IV_LEN
    cipher.iv = iv
    
    File.open(out_path, 'wb') do |out_f|
      out_f.write(salt)
      out_f.write(iv)
      
      File.open(tar_path, 'rb') do |tar_f|
        while chunk = tar_f.read(16384)
          out_f.write(cipher.update(chunk))
        end
      end
      out_f.write(cipher.final)
      out_f.write(cipher.auth_tag)
    end
    
    { path: out_path, size: File.size(out_path) }
  ensure
    File.delete(tar_path) if File.exist?(tar_path)
  end
end