Class: Digest::SHA2

Inherits:
Class
  • Object
show all
Defined in:
sha2/lib/sha2.rb

Overview

A meta digest provider class for SHA256, SHA384 and SHA512.

Instance Method Summary collapse

Methods inherited from Class

base64digest, bubblebabble, digest, file, hexdigest

Methods included from Instance

#==, #base64digest, #base64digest!, #bubblebabble, #digest, #digest!, #file, #hexdigest, #hexdigest!, #length, #new, #size, #to_s

Constructor Details

#initialize(bitlen = 256) ⇒ SHA2

call-seq:

Digest::SHA2.new(bitlen = 256) -> digest_obj

Creates a new SHA2 hash object with a given bit length.

Valid bit lengths are 256, 384 and 512.


26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'sha2/lib/sha2.rb', line 26

def initialize(bitlen = 256)
  case bitlen
  when 256
    @sha2 = Digest::SHA256.new
  when 384
    @sha2 = Digest::SHA384.new
  when 512
    @sha2 = Digest::SHA512.new
  else
    raise ArgumentError, "unsupported bit length: %s" % bitlen.inspect
  end
  @bitlen = bitlen
end

Instance Method Details

#block_lengthObject

call-seq:

digest_obj.block_length -> Integer

Returns the block length of the digest in bytes.

Digest::SHA256.new.block_length * 8
# => 512
Digest::SHA384.new.block_length * 8
# => 1024
Digest::SHA512.new.block_length * 8
# => 1024

77
78
79
# File 'sha2/lib/sha2.rb', line 77

def block_length
  @sha2.block_length
end

#digest_lengthObject

call-seq:

digest_obj.digest_length -> Integer

Returns the length of the hash value of the digest in bytes.

Digest::SHA256.new.digest_length * 8
# => 256
Digest::SHA384.new.digest_length * 8
# => 384
Digest::SHA512.new.digest_length * 8
# => 512

For example, digests produced by Digest::SHA256 will always be 32 bytes (256 bits) in size.


95
96
97
# File 'sha2/lib/sha2.rb', line 95

def digest_length
  @sha2.digest_length
end

#initialize_copy(other) ⇒ Object

:nodoc:


99
100
101
# File 'sha2/lib/sha2.rb', line 99

def initialize_copy(other) # :nodoc:
  @sha2 = other.instance_eval { @sha2.clone }
end

#inspectObject

:nodoc:


103
104
105
# File 'sha2/lib/sha2.rb', line 103

def inspect # :nodoc:
  "#<%s:%d %s>" % [self.class.name, @bitlen, hexdigest]
end

#resetObject

call-seq:

digest_obj.reset -> digest_obj

Resets the digest to the initial state and returns self.


44
45
46
47
# File 'sha2/lib/sha2.rb', line 44

def reset
  @sha2.reset
  self
end

#update(str) ⇒ Object Also known as: <<

call-seq:

digest_obj.update(string) -> digest_obj
digest_obj << string -> digest_obj

Updates the digest using a given string and returns self.


54
55
56
57
# File 'sha2/lib/sha2.rb', line 54

def update(str)
  @sha2.update(str)
  self
end