Module: NauktisUtils::FileDigester

Defined in:
lib/nauktis_utils/file_digester.rb

Constant Summary collapse

ALGORITHMS =
[:md5, :sha1, :sha256, :sha512, :sha3]

Class Method Summary collapse

Class Method Details

.digest(filename, algorithm = :sha1) ⇒ Object

Returns the hexdigest of the file provided.



6
7
8
9
10
11
12
13
14
# File 'lib/nauktis_utils/file_digester.rb', line 6

def self.digest(filename, algorithm = :sha1)
  full_path = FileBrowser.ensure_valid_file(filename)
  raise "Unknown algorithm #{algorithm}, use #{ALGORITHMS}" unless ALGORITHMS.include?(algorithm.to_sym)
  if algorithm.to_sym == :sha3
    SHA3::Digest.file(full_path).hexdigest
  else
    OpenSSL::Digest.new(algorithm.to_s).file(full_path).hexdigest
  end
end

.digest_file_valid?(filename) ⇒ Boolean

Checks the digest files next to the file provided. Returns true if all the digest files contain proper digest

Returns:

  • (Boolean)


24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/nauktis_utils/file_digester.rb', line 24

def self.digest_file_valid?(filename)
  full_path = FileBrowser.ensure_valid_file(filename)
  valid = true
  ALGORITHMS.each do |algorithm|
    digest_file = "#{full_path}.#{algorithm}"
    if FileBrowser.valid_file?(digest_file)
      unless self.digest(filename, algorithm) == File.read(digest_file)
        valid = false
        break
      end
    end
  end
  valid
end

.generate_digest_file(filename, algorithm = :sha1) ⇒ Object

Generates a file next to the file provided containing its digest



17
18
19
20
# File 'lib/nauktis_utils/file_digester.rb', line 17

def self.generate_digest_file(filename, algorithm = :sha1)
  digest = self.digest(filename, algorithm)
  File.write("#{File.expand_path(filename)}.#{algorithm}", digest)
end