class Shrine::Plugins::Signature::SignatureCalculator

Constants

SUPPORTED_ALGORITHMS
SUPPORTED_FORMATS

Attributes

algorithm[R]
format[R]

Public Class Methods

new(algorithm, format:) click to toggle source
# File lib/shrine/plugins/signature.rb, line 58
def initialize(algorithm, format:)
  raise Error, "unknown hash algorithm #{algorithm.inspect}, supported algorithms are: #{SUPPORTED_ALGORITHMS.join(",")}" unless SUPPORTED_ALGORITHMS.include?(algorithm)
  raise Error, "unknown hash format #{format.inspect}, supported formats are: #{SUPPORTED_FORMATS.join(",")}" unless SUPPORTED_FORMATS.include?(format)

  @algorithm = algorithm
  @format    = format
end

Public Instance Methods

call(io) click to toggle source
# File lib/shrine/plugins/signature.rb, line 66
def call(io)
  hash = send(:"calculate_#{algorithm}", io)
  send(:"encode_#{format}", hash)
end

Private Instance Methods

calculate_crc32(io) click to toggle source
# File lib/shrine/plugins/signature.rb, line 93
def calculate_crc32(io)
  require "zlib"
  crc = 0
  crc = Zlib.crc32(io.read(16*1024, buffer ||= String.new), crc) until io.eof?
  crc.to_s
end
calculate_digest(name, io) click to toggle source
# File lib/shrine/plugins/signature.rb, line 100
def calculate_digest(name, io)
  require "digest"
  digest = Digest.const_get(name).new
  digest.update(io.read(16*1024, buffer ||= String.new)) until io.eof?
  digest.digest
end
calculate_md5(io) click to toggle source
# File lib/shrine/plugins/signature.rb, line 89
def calculate_md5(io)
  calculate_digest(:MD5, io)
end
calculate_sha1(io) click to toggle source
# File lib/shrine/plugins/signature.rb, line 73
def calculate_sha1(io)
  calculate_digest(:SHA1, io)
end
calculate_sha256(io) click to toggle source
# File lib/shrine/plugins/signature.rb, line 77
def calculate_sha256(io)
  calculate_digest(:SHA256, io)
end
calculate_sha384(io) click to toggle source
# File lib/shrine/plugins/signature.rb, line 81
def calculate_sha384(io)
  calculate_digest(:SHA384, io)
end
calculate_sha512(io) click to toggle source
# File lib/shrine/plugins/signature.rb, line 85
def calculate_sha512(io)
  calculate_digest(:SHA512, io)
end
encode_base64(hash) click to toggle source
# File lib/shrine/plugins/signature.rb, line 115
def encode_base64(hash)
  require "base64"
  Base64.strict_encode64(hash)
end
encode_hex(hash) click to toggle source
# File lib/shrine/plugins/signature.rb, line 111
def encode_hex(hash)
  hash.unpack("H*").first
end
encode_none(hash) click to toggle source
# File lib/shrine/plugins/signature.rb, line 107
def encode_none(hash)
  hash
end