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