add_bits#

Feed an arbitrary number of bits into a Digest::SHA object.

Unlike add, this method is not restricted to whole bytes. It accepts two call forms:

  • One-argument form add_bits($bitstr) hashes a string of '0' and '1' characters - the hash takes one bit per character, so "01011010" adds exactly 8 bits of input.

  • Two-argument form add_bits($data, $numbits) hashes the first $numbits bits of the packed binary string $data. If $numbits exceeds 8 * length($data) it is capped at that value.

Most of the SHA standard is defined on bit-strings rather than byte-strings; this is the entry point for the bit-exact test vectors in FIPS 180-4.

Synopsis#

$sha->add_bits("11001010");          # 8 bits from ASCII 0/1 string
$sha->add_bits($packed, 13);         # first 13 bits of $packed

What you get back#

The receiver, for chaining.

Examples#

my $sha = Digest::SHA->new(256);
$sha->add_bits("01011010" x 8);   # 64 bits
print $sha->hexdigest;
# FIPS 180-4 1-bit test vector for SHA-1
my $sha = Digest::SHA->new(1);
$sha->add_bits("0");
print $sha->hexdigest;
# bb6b3e18f0115b57925241676f5b1ae88747b08a
my $sha = Digest::SHA->new(256);
$sha->add_bits("\xab\xcd", 12);  # first 12 bits of 0xabcd

Edge cases#

  • The one-argument form packs the string with pack("B*", ...), so every character counts as one bit: a character other than '0' or '1' is not skipped but read by its lowest bit. An empty string is a no-op.

  • In the two-argument form, a zero bit count leaves the hash state untouched, and a negative one hashes all of $data.

  • Called on a reference that is not a Digest::SHA object, returns that reference unchanged.

Differences from upstream#

  • A negative bit count in the two-argument form hashes all of $data; upstream hands it to XS as a huge unsigned count, reads past the end of the string and crashes.

  • Called on a reference that is not a Digest::SHA object, upstream crashes with a segmentation fault (its XS shawrite is handed a null context); pperl leaves the reference alone and returns it.

See also#

  • add - standard byte-aligned input path; use it unless you truly have sub-byte data.

  • digest - finalises the running hash once input is complete.

  • addfile - byte-oriented file ingestion.