Skip to content

Commit

Permalink
OpenSSLHash: Expose hash_size() and block_size()
Browse files Browse the repository at this point in the history
Summary:
Given an folly::OpenSSLHash::Digest, which can represent any number of message
digests, expose several functions to query properties of the underlying
message digest algorithm. This is useful when the algorithm is given an
arbitrary `Digest` object that was created by a caller, and would like to,
for instance, determine the size of the message digest.

Reviewed By: zalecodez

Differential Revision: D62269695

fbshipit-source-id: 009818bd62d30d31b143ea984bf455b01a7e48ef
  • Loading branch information
Mingtao Yang authored and facebook-github-bot committed Sep 9, 2024
1 parent eb62400 commit 3184d5a
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 2 deletions.
18 changes: 16 additions & 2 deletions folly/ssl/OpenSSLHash.h
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,6 @@
namespace folly {
namespace ssl {

/// Warning:
/// These functions are not thread-safe unless you initialize OpenSSL.
class OpenSSLHash {
public:
class Digest {
Expand Down Expand Up @@ -96,6 +94,22 @@ class OpenSSLHash {
hash_reset();
}

size_t hash_size() const {
if (nullptr == ctx_) {
throw_exception<std::runtime_error>(
"hash_size() called without hash_init()");
}
return EVP_MD_size(md_);
}

size_t block_size() const {
if (nullptr == ctx_) {
throw_exception<std::runtime_error>(
"block_size() called without hash_init()");
}
return EVP_MD_block_size(md_);
}

private:
const EVP_MD* md_{nullptr};
EvpMdCtxUniquePtr ctx_{nullptr};
Expand Down
15 changes: 15 additions & 0 deletions folly/ssl/test/OpenSSLHashTest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -487,3 +487,18 @@ TEST_F(OpenSSLHashTest, hmac_final_without_init_throws) {
std::array<uint8_t, 32> out;
EXPECT_THROW(hmac.hash_final(range(out)), std::runtime_error);
}

TEST_F(OpenSSLHashTest, HashAndBlockSizes) {
OpenSSLHash::Digest d;
d.hash_init(EVP_sha256());
EXPECT_EQ(d.hash_size(), 32);
EXPECT_EQ(d.block_size(), 64);

d.hash_init(EVP_sha384());
EXPECT_EQ(d.hash_size(), 48);
EXPECT_EQ(d.block_size(), 128);

d.hash_init(EVP_sha512());
EXPECT_EQ(d.hash_size(), 64);
EXPECT_EQ(d.block_size(), 128);
}

0 comments on commit 3184d5a

Please sign in to comment.