Class: Cryptosphere::Blob::Builder

Inherits:
Object
  • Object
show all
Defined in:
lib/cryptosphere/blobs/blob.rb

Overview

Encrypt a node and insert it into the local store

Instance Method Summary collapse

Constructor Details

#initializeBuilder

Returns a new instance of Builder.



64
65
66
67
68
69
# File 'lib/cryptosphere/blobs/blob.rb', line 64

def initialize
  @hash_function = Cryptosphere.hash_function
  @hash_function << PREFIX

  @file = Tempfile.new 'cryptosphere'
end

Instance Method Details

#finishObject



77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
# File 'lib/cryptosphere/blobs/blob.rb', line 77

def finish
  keys = Cryptosphere.kdf(@hash_function.digest, size: 64)
  key, iv = keys[0...32], keys[32...64]

  block_cipher = Cryptosphere.block_cipher
  block_cipher.encrypt
  block_cipher.key, block_cipher.iv = key, iv

  @file.rewind
  output = Tempfile.new 'cryptosphere'

  begin
    hash_function = Cryptosphere.hash_function
    while plaintext = @file.read(4096)
      ciphertext = block_cipher.update(plaintext)
      output << ciphertext
      hash_function << ciphertext
    end

    ciphertext = block_cipher.final
    output << ciphertext
    hash_function << ciphertext
    output.close

    node_id = hash_function.hexdigest
    FileUtils.mv output.path, File.join(Blob.path, node_id)

    Blob.new(node_id, key + iv)
  rescue Exception
    output.close rescue nil
    output.unlink rescue nil

    raise
  end
ensure
  @file.close rescue nil
  @file.unlink rescue nil
end

#write(data) ⇒ Object Also known as: <<



71
72
73
74
# File 'lib/cryptosphere/blobs/blob.rb', line 71

def write(data)
  @hash_function << data
  @file << data
end