From bb6c0b8e13151e4484ea375a40f19ad80d5a6919 Mon Sep 17 00:00:00 2001 From: Xiaohan Wang Date: Tue, 24 Oct 2017 01:18:01 +0000 Subject: [PATCH] crypto: Add SecureHashTest.Equality test Make sure Update(a) + Update(b) == Update(a + b), which is not obvious for readers not familiar with crypto. Also updates the comment to emphasize this. Change-Id: Iae8adeb4743c247053d60c7040e7d79807ce9475 Reviewed-on: https://chromium-review.googlesource.com/729701 Reviewed-by: David Benjamin Commit-Queue: Xiaohan Wang Cr-Commit-Position: refs/heads/master@{#510979} --- crypto/secure_hash.h | 3 ++- crypto/secure_hash_unittest.cc | 25 +++++++++++++++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/crypto/secure_hash.h b/crypto/secure_hash.h index 30b9fdc5f283fa..b97487b5ca73f6 100644 --- a/crypto/secure_hash.h +++ b/crypto/secure_hash.h @@ -15,7 +15,8 @@ namespace crypto { // A wrapper to calculate secure hashes incrementally, allowing to -// be used when the full input is not known in advance. +// be used when the full input is not known in advance. The end result will the +// same as if we have the full input in advance. class CRYPTO_EXPORT SecureHash { public: enum Algorithm { diff --git a/crypto/secure_hash_unittest.cc b/crypto/secure_hash_unittest.cc index cb9f5852327e69..b54a83701c0928 100644 --- a/crypto/secure_hash_unittest.cc +++ b/crypto/secure_hash_unittest.cc @@ -80,3 +80,28 @@ TEST(SecureHashTest, TestLength) { crypto::SecureHash::Create(crypto::SecureHash::SHA256)); EXPECT_EQ(crypto::kSHA256Length, ctx->GetHashLength()); } + +TEST(SecureHashTest, Equality) { + std::string input1(10001, 'a'); // 'a' repeated 10001 times + std::string input2(10001, 'd'); // 'd' repeated 10001 times + + uint8_t output1[crypto::kSHA256Length]; + uint8_t output2[crypto::kSHA256Length]; + + // Call Update() twice on input1 and input2. + std::unique_ptr ctx1( + crypto::SecureHash::Create(crypto::SecureHash::SHA256)); + ctx1->Update(input1.data(), input1.size()); + ctx1->Update(input2.data(), input2.size()); + ctx1->Finish(output1, sizeof(output1)); + + // Call Update() once one input1 + input2 (concatenation). + std::unique_ptr ctx2( + crypto::SecureHash::Create(crypto::SecureHash::SHA256)); + std::string input3 = input1 + input2; + ctx2->Update(input3.data(), input3.size()); + ctx2->Finish(output2, sizeof(output2)); + + // The hash should be the same. + EXPECT_EQ(0, memcmp(output1, output2, crypto::kSHA256Length)); +}