xref: /aosp_15_r20/external/gsc-utils/tpm_generated/secure_hash.cc (revision 4f2df630800bdcf1d4f0decf95d8a1cb87344f5f)
1 // Copyright 2012 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include "secure_hash.h"
6 
7 #if defined(OPENSSL_IS_BORINGSSL)
8 #include <openssl/mem.h>
9 #else
10 #include <openssl/crypto.h>
11 #endif
12 #include <openssl/sha.h>
13 #include <stddef.h>
14 
15 #include <android-base/logging.h>
16 
17 namespace crypto {
18 
19 namespace {
20 
21 class SecureHashSHA256 : public SecureHash {
22  public:
SecureHashSHA256()23   SecureHashSHA256() {
24     SHA256_Init(&ctx_);
25   }
26 
SecureHashSHA256(const SecureHashSHA256 & other)27   SecureHashSHA256(const SecureHashSHA256& other) : SecureHash() {
28     memcpy(&ctx_, &other.ctx_, sizeof(ctx_));
29   }
30 
~SecureHashSHA256()31   ~SecureHashSHA256() override {
32     OPENSSL_cleanse(&ctx_, sizeof(ctx_));
33   }
34 
Update(const void * input,size_t len)35   void Update(const void* input, size_t len) override {
36     SHA256_Update(&ctx_, static_cast<const unsigned char*>(input), len);
37   }
38 
Finish(void * output,size_t len)39   void Finish(void* output, size_t len) override {
40     CHECK(len >= SHA256_DIGEST_LENGTH);
41     SHA256_Final(static_cast<uint8_t*>(output), &ctx_);
42   }
43 
Clone() const44   SecureHash* Clone() const override {
45     return new SecureHashSHA256(*this);
46   }
47 
GetHashLength() const48   size_t GetHashLength() const override { return SHA256_DIGEST_LENGTH; }
49 
50  private:
51   SHA256_CTX ctx_;
52 };
53 
54 }  // namespace
55 
Create(Algorithm algorithm)56 SecureHash* SecureHash::Create(Algorithm algorithm) {
57   switch (algorithm) {
58     case SHA256:
59       return new SecureHashSHA256();
60     default:
61       LOG(ERROR) << "SecureHash not implemented for algorithm " << algorithm;
62       return NULL;
63   }
64 }
65 
66 }  // namespace crypto
67