1 // Copyright 2012 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "crypto/secure_hash.h"
9 #include "base/memory/ptr_util.h"
10 #include "base/notreached.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"
20 class SecureHashSHA256 : public SecureHash {
23 // Ensure that CPU features detection is performed before using
24 // BoringSSL. This will enable hw accelerated implementations.
29 SecureHashSHA256(const SecureHashSHA256& other) {
30 memcpy(&ctx_, &other.ctx_, sizeof(ctx_));
33 ~SecureHashSHA256() override {
34 OPENSSL_cleanse(&ctx_, sizeof(ctx_));
37 void Update(const void* input, size_t len) override {
38 SHA256_Update(&ctx_, static_cast<const unsigned char*>(input), len);
41 void Finish(void* output, size_t len) override {
42 ScopedOpenSSLSafeSizeBuffer<SHA256_DIGEST_LENGTH> result(
43 static_cast<unsigned char*>(output), len);
44 SHA256_Final(result.safe_buffer(), &ctx_);
47 std::unique_ptr<SecureHash> Clone() const override {
48 return std::make_unique<SecureHashSHA256>(*this);
51 size_t GetHashLength() const override { return SHA256_DIGEST_LENGTH; }
57 class SecureHashSHA512 : public SecureHash {
60 // Ensure that CPU features detection is performed before using
61 // BoringSSL. This will enable hw accelerated implementations.
66 SecureHashSHA512(const SecureHashSHA512& other) {
67 memcpy(&ctx_, &other.ctx_, sizeof(ctx_));
70 ~SecureHashSHA512() override { OPENSSL_cleanse(&ctx_, sizeof(ctx_)); }
72 void Update(const void* input, size_t len) override {
73 SHA512_Update(&ctx_, static_cast<const unsigned char*>(input), len);
76 void Finish(void* output, size_t len) override {
77 ScopedOpenSSLSafeSizeBuffer<SHA512_DIGEST_LENGTH> result(
78 static_cast<unsigned char*>(output), len);
79 SHA512_Final(result.safe_buffer(), &ctx_);
82 std::unique_ptr<SecureHash> Clone() const override {
83 return std::make_unique<SecureHashSHA512>(*this);
86 size_t GetHashLength() const override { return SHA512_DIGEST_LENGTH; }
94 std::unique_ptr<SecureHash> SecureHash::Create(Algorithm algorithm) {
97 return std::make_unique<SecureHashSHA256>();
99 return std::make_unique<SecureHashSHA512>();
106 } // namespace crypto