secure_hash.cc 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // Copyright (c) 2012 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. #include "crypto/secure_hash.h"
  5. #include <stddef.h>
  6. #include "base/memory/ptr_util.h"
  7. #include "base/notreached.h"
  8. #include "base/pickle.h"
  9. #include "crypto/openssl_util.h"
  10. #include "third_party/boringssl/src/include/openssl/mem.h"
  11. #include "third_party/boringssl/src/include/openssl/sha.h"
  12. namespace crypto {
  13. namespace {
  14. class SecureHashSHA256 : public SecureHash {
  15. public:
  16. SecureHashSHA256() {
  17. // Ensure that CPU features detection is performed before using
  18. // BoringSSL. This will enable hw accelerated implementations.
  19. EnsureOpenSSLInit();
  20. SHA256_Init(&ctx_);
  21. }
  22. SecureHashSHA256(const SecureHashSHA256& other) {
  23. memcpy(&ctx_, &other.ctx_, sizeof(ctx_));
  24. }
  25. ~SecureHashSHA256() override {
  26. OPENSSL_cleanse(&ctx_, sizeof(ctx_));
  27. }
  28. void Update(const void* input, size_t len) override {
  29. SHA256_Update(&ctx_, static_cast<const unsigned char*>(input), len);
  30. }
  31. void Finish(void* output, size_t len) override {
  32. ScopedOpenSSLSafeSizeBuffer<SHA256_DIGEST_LENGTH> result(
  33. static_cast<unsigned char*>(output), len);
  34. SHA256_Final(result.safe_buffer(), &ctx_);
  35. }
  36. std::unique_ptr<SecureHash> Clone() const override {
  37. return std::make_unique<SecureHashSHA256>(*this);
  38. }
  39. size_t GetHashLength() const override { return SHA256_DIGEST_LENGTH; }
  40. private:
  41. SHA256_CTX ctx_;
  42. };
  43. } // namespace
  44. std::unique_ptr<SecureHash> SecureHash::Create(Algorithm algorithm) {
  45. switch (algorithm) {
  46. case SHA256:
  47. return std::make_unique<SecureHashSHA256>();
  48. default:
  49. NOTIMPLEMENTED();
  50. return nullptr;
  51. }
  52. }
  53. } // namespace crypto