kythe.io@v0.0.68-0.20240422202219-7225dbc01741/kythe/cxx/common/sha256_hasher.cc (about)

     1  /*
     2   * Copyright 2023 The Kythe Authors. All rights reserved.
     3   *
     4   * Licensed under the Apache License, Version 2.0 (the "License");
     5   * you may not use this file except in compliance with the License.
     6   * You may obtain a copy of the License at
     7   *
     8   *   http://www.apache.org/licenses/LICENSE-2.0
     9   *
    10   * Unless required by applicable law or agreed to in writing, software
    11   * distributed under the License is distributed on an "AS IS" BASIS,
    12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13   * See the License for the specific language governing permissions and
    14   * limitations under the License.
    15   */
    16  
    17  #include "kythe/cxx/common/sha256_hasher.h"
    18  
    19  #include <openssl/sha.h>
    20  
    21  #include <array>
    22  #include <cstddef>
    23  #include <string>
    24  #include <utility>
    25  
    26  #include "absl/strings/escaping.h"
    27  
    28  namespace kythe {
    29  Sha256Hasher::Sha256Hasher() { ::SHA256_Init(&context_); }
    30  
    31  Sha256Hasher& Sha256Hasher::Update(Sha256Hasher::ByteView data) & {
    32    ::SHA256_Update(&context_, data.data(), data.size());
    33    return *this;
    34  }
    35  
    36  Sha256Hasher&& Sha256Hasher::Update(Sha256Hasher::ByteView data) && {
    37    return std::move(Update(data));
    38  }
    39  
    40  std::array<std::byte, SHA256_DIGEST_LENGTH> Sha256Hasher::Finish() && {
    41    std::array<std::byte, SHA256_DIGEST_LENGTH> result;
    42    std::move(*this).Finish(result.data());
    43    return result;
    44  }
    45  
    46  void Sha256Hasher::Finish(std::byte* out) && {
    47    ::SHA256_Final(reinterpret_cast<unsigned char*>(out), &context_);
    48  }
    49  
    50  std::string Sha256Hasher::FinishBinString() && {
    51    std::string result(SHA256_DIGEST_LENGTH, '\0');
    52    ::SHA256_Final(reinterpret_cast<unsigned char*>(result.data()), &context_);
    53    return result;
    54  }
    55  
    56  std::string Sha256Hasher::FinishHexString() && {
    57    return absl::BytesToHexString(std::move(*this).FinishBinString());
    58  }
    59  
    60  }  // namespace kythe