BDE 4.14.0 Production release
Loading...
Searching...
No Matches

Detailed Description

Outline

Purpose

Provide a value-semantic type encoding a message in a SHA-2 digest.

Classes

See also
bdlde_md5

Description

This component provides a set of classes (Sha224, Sha256, Sha384, and Sha512) that implement a mechanism for computing and updating a SHA-2 digest (a cryptographic hash). The specification for this is based on FIPS-180, which can be found at

http://csrc.nist.gov/publications/fips/fips180-4/fips-180-4.pdf

Note that a SHA-2 digest does not aid in error correction.

Usage

This section illustrates intended use of this component.

Example 1: Basic Usage

The validatePassword function below returns whether a specified password has a specified hash value. The assertPasswordIsExpected function below has a sample password to hash and a hash value that matches it. Note that the output of loadDigest is a binary representation. When hashes are displayed for human consumption, they are typically converted to hex, but that would create unnecessary overhead here.

/// Return `true` if the specified `password` concatenated with the
/// specified `salt` has a SHA-512 hash equal to the specified
/// `expected`, and `false` otherwise.
bool validatePassword(const bsl::string& password,
const bsl::string& salt,
const unsigned char *expected)
{
bdlde::Sha512 hasher;
hasher.update(password.c_str(), password.length());
hasher.update(salt.c_str(), salt.length());
unsigned char digest[bdlde::Sha512::k_DIGEST_SIZE];
hasher.loadDigest(digest);
return bsl::equal(digest,
expected);
}
/// Asserts that the constant string `pass` salted with `word` has the
/// expected hash value. In a real application, the expected hash would
/// likely come from some sort of database.
void assertPasswordIsExpected()
{
const bsl::string password = "pass";
const bsl::string salt = "word";
const unsigned char expected[bdlde::Sha512::k_DIGEST_SIZE] = {
0xB1, 0x09, 0xF3, 0xBB, 0xBC, 0x24, 0x4E, 0xB8, 0x24, 0x41, 0x91,
0x7E, 0xD0, 0x6D, 0x61, 0x8B, 0x90, 0x08, 0xDD, 0x09, 0xB3, 0xBE,
0xFD, 0x1B, 0x5E, 0x07, 0x39, 0x4C, 0x70, 0x6A, 0x8B, 0xB9, 0x80,
0xB1, 0xD7, 0x78, 0x5E, 0x59, 0x76, 0xEC, 0x04, 0x9B, 0x46, 0xDF,
0x5F, 0x13, 0x26, 0xAF, 0x5A, 0x2E, 0xA6, 0xD1, 0x03, 0xFD, 0x07,
0xC9, 0x53, 0x85, 0xFF, 0xAB, 0x0C, 0xAC, 0xBC, 0x86
};
ASSERT(validatePassword(password, salt, expected));
}
Definition bdlde_sha2.h:406
static const bsl::size_t k_DIGEST_SIZE
The size (in bytes) of the output.
Definition bdlde_sha2.h:426
void update(const void *data, bsl::size_t length)
void loadDigest(unsigned char *result) const
Load the value of this SHA-2 digest into the specified result.
Definition bslstl_string.h:1281
size_type length() const BSLS_KEYWORD_NOEXCEPT
Definition bslstl_string.h:6601
const CHAR_TYPE * c_str() const BSLS_KEYWORD_NOEXCEPT
Definition bslstl_string.h:6705