xref: /aosp_15_r20/external/openscreen/util/crypto/sha2.cc (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 #include "util/crypto/sha2.h"
6 
7 #include <stddef.h>
8 
9 #include <memory>
10 
11 #include "util/crypto/secure_hash.h"
12 #include "util/std_util.h"
13 
14 namespace openscreen {
15 
SHA256HashString(absl::string_view str,uint8_t output[SHA256_DIGEST_LENGTH])16 Error SHA256HashString(absl::string_view str,
17                        uint8_t output[SHA256_DIGEST_LENGTH]) {
18   bssl::UniquePtr<EVP_MD_CTX> context(EVP_MD_CTX_new());
19   if (!EVP_Digest(str.data(), str.size(), output, nullptr, EVP_sha256(),
20                   nullptr)) {
21     return Error::Code::kSha256HashFailure;
22   }
23 
24   return Error::None();
25 }
26 
SHA256HashString(absl::string_view str)27 ErrorOr<std::string> SHA256HashString(absl::string_view str) {
28   std::string output(SHA256_DIGEST_LENGTH, 0);
29   const Error error =
30       SHA256HashString(str, reinterpret_cast<uint8_t*>(data(output)));
31   if (error != Error::None()) {
32     return error;
33   }
34 
35   return output;
36 }
37 
38 }  // namespace openscreen
39