class Aws::TreeHash

Used for computing a tree hash SHA256 checksum of an object.

tree_hash = TreeHash.new
tree_hash.update(file.read(1024 * 1024)) until file.eof?
tree_hash.digest

Limitations and Notes

There are two main limitations to be aware of when using TreeHash:

If you have a large object/file, and you would like to compute the chunks concurrently, you must break the original file/data into sections that are evenly divisible by 1MB. Each section of data requires a seperate TreeHash object to compute hashes. Once all sections of data are complete, you can rejoin their {#hashes} in sequential order into a single TreeHash, then call {#digest} on the final tree hash.

Attributes

hashes[RW]

@return [Array<String>] The built up list of hashes. Each hash is

a sha255 digest of a 1MB chunk.

Public Class Methods

new(hashes = []) click to toggle source
# File lib/aws-sdk-core/tree_hash.rb, line 33
def initialize(hashes = [])
  @digest = OpenSSL::Digest.new('sha256')
  @hashes = hashes
end

Public Instance Methods

digest() click to toggle source
# File lib/aws-sdk-core/tree_hash.rb, line 50
def digest
  hashes = @hashes
  digest = OpenSSL::Digest.new('sha256')
  until hashes.count == 1
    hashes = hashes.each_slice(2).map do |h1,h2|
      digest.reset
      if h2
        digest.update(h1)
        digest.update(h2)
        digest.digest
      else
        h1
      end
    end
  end
  hashes.first.bytes.map{|x| x.to_i.to_s(16).rjust(2, '0')}.join('')
end
update(chunk) click to toggle source

@param [String] chunk @return [String] Returns the computed SHA256 digest of the chunk.

# File lib/aws-sdk-core/tree_hash.rb, line 44
def update(chunk)
  @hashes << @digest.update(chunk).digest
  @digest.reset
  @hashes.last
end