new#

Construct or reinitialise a Digest::SHA object.

The primary object constructor. Works as both a class method (Digest::SHA->new(256)) and an instance method ($sha->new(512)), and accepts the algorithm in any of the shapes Digest::SHA recognises: an integer like 256, a string like "SHA-256", "sha256", or "512/224". When called without an algorithm argument it defaults to SHA-1.

As an instance method, new reuses the existing object: supplying a new algorithm resets state and switches to that algorithm; omitting it simply rewinds the state (same as reset).

Synopsis#

my $sha = Digest::SHA->new(256);
my $sha = Digest::SHA->new("SHA-512/256");
$sha->new;                       # rewind, keep algorithm
$sha->new(384);                  # rewind, switch to SHA-384

What you get back#

A blessed Digest::SHA object, or undef when the algorithm argument cannot be parsed as a supported algorithm.

Examples#

my $sha = Digest::SHA->new("sha256");
$sha->add("The quick brown fox ", "jumps over the lazy dog");
print $sha->hexdigest;

## d7a8fbb307d7809469ca9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592
my $sha = Digest::SHA->new(512);
$sha->add_bits("01011010");       # hash exactly 8 bits
my $sha = Digest::SHA->new(256);
$sha->add("first");
$sha->new(512);                   # rewind and switch
$sha->add("second");              # now hashing with SHA-512

Edge cases#

  • No algorithm argument defaults to SHA-1.

  • An unparseable algorithm returns undef; check the return value before chaining ->add.

  • Called on an existing object, new mutates that object in place and returns it — it does not allocate a second context.

Differences from upstream#

Fully compatible with upstream Digest::SHA 6.04.

See also#

  • reset — explicit rewind, same semantics as the no-argument instance form.

  • clone — copy the current state into a fresh object.

  • newSHA — lower-level XS constructor taking an integer algorithm code.