xref: /aosp_15_r20/external/openscreen/util/crypto/secure_hash.h (revision 3f982cf4871df8771c9d4abe6e9a6f8d829b2736)
1 // Copyright 2019 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #ifndef UTIL_CRYPTO_SECURE_HASH_H_
6 #define UTIL_CRYPTO_SECURE_HASH_H_
7 
8 #include <stddef.h>
9 
10 #include <memory>
11 #include <string>
12 
13 #include "openssl/base.h"
14 #include "openssl/evp.h"
15 #include "platform/base/macros.h"
16 
17 namespace openscreen {
18 
19 // A wrapper to calculate secure hashes incrementally, allowing to
20 // be used when the full input is not known in advance. The end result will the
21 // same as if we have the full input in advance.
22 class SecureHash {
23  public:
24   explicit SecureHash(const EVP_MD* type);
25   SecureHash(const SecureHash& other);
26   SecureHash(SecureHash&& other);
27   SecureHash& operator=(const SecureHash& other);
28   SecureHash& operator=(SecureHash&& other);
29 
30   ~SecureHash();
31 
32   void Update(const uint8_t* input, size_t len);
33   void Finish(uint8_t* output);
34 
35   // Handy versions that do the kludgy casting to unsigned in the background.
36   void Update(const std::string& input);
37   void Finish(char* output);
38 
39   size_t GetHashLength() const;
40 
41  private:
42   bssl::UniquePtr<EVP_MD_CTX> ctx_ =
43       bssl::UniquePtr<EVP_MD_CTX>(EVP_MD_CTX_new());
44 };
45 
46 }  // namespace openscreen
47 
48 #endif  // UTIL_CRYPTO_SECURE_HASH_H_
49