Upload upstream chromium 67.0.3396
[platform/framework/web/chromium-efl.git] / crypto / secure_hash.cc
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
5 #include "crypto/secure_hash.h"
6
7 #include <stddef.h>
8
9 #include "base/logging.h"
10 #include "base/memory/ptr_util.h"
11 #include "base/pickle.h"
12 #include "crypto/openssl_util.h"
13 #include "third_party/boringssl/src/include/openssl/mem.h"
14 #include "third_party/boringssl/src/include/openssl/sha.h"
15
16 namespace crypto {
17
18 namespace {
19
20 class SecureHashSHA256 : public SecureHash {
21  public:
22   SecureHashSHA256() {
23     SHA256_Init(&ctx_);
24   }
25
26   SecureHashSHA256(const SecureHashSHA256& other) {
27     memcpy(&ctx_, &other.ctx_, sizeof(ctx_));
28   }
29
30   ~SecureHashSHA256() override {
31     OPENSSL_cleanse(&ctx_, sizeof(ctx_));
32   }
33
34   void Update(const void* input, size_t len) override {
35     SHA256_Update(&ctx_, static_cast<const unsigned char*>(input), len);
36   }
37
38   void Finish(void* output, size_t len) override {
39     ScopedOpenSSLSafeSizeBuffer<SHA256_DIGEST_LENGTH> result(
40         static_cast<unsigned char*>(output), len);
41     SHA256_Final(result.safe_buffer(), &ctx_);
42   }
43
44   std::unique_ptr<SecureHash> Clone() const override {
45     return std::make_unique<SecureHashSHA256>(*this);
46   }
47
48   size_t GetHashLength() const override { return SHA256_DIGEST_LENGTH; }
49
50  private:
51   SHA256_CTX ctx_;
52 };
53
54 }  // namespace
55
56 std::unique_ptr<SecureHash> SecureHash::Create(Algorithm algorithm) {
57   switch (algorithm) {
58     case SHA256:
59       return std::make_unique<SecureHashSHA256>();
60     default:
61       NOTIMPLEMENTED();
62       return nullptr;
63   }
64 }
65
66 }  // namespace crypto