OLD | NEW |
1 // Copyright (c) 2010 The Chromium Authors. All rights reserved. | 1 // Copyright (c) 2010 The Chromium Authors. All rights reserved. |
2 // Use of this source code is governed by a BSD-style license that can be | 2 // Use of this source code is governed by a BSD-style license that can be |
3 // found in the LICENSE file. | 3 // found in the LICENSE file. |
4 | 4 |
5 #include "base/sha2.h" | 5 #include "base/sha2.h" |
6 | 6 |
7 #include <openssl/ssl.h> | 7 #include <openssl/ssl.h> |
8 | 8 |
9 #include "base/basictypes.h" | 9 #include "base/basictypes.h" |
10 #include "base/openssl_util.h" | 10 #include "base/openssl_util.h" |
11 #include "base/stl_util-inl.h" | 11 #include "base/stl_util-inl.h" |
12 | 12 |
13 namespace base { | 13 namespace base { |
14 | 14 |
15 void SHA256HashString(const std::string& str, void* output, size_t len) { | 15 void SHA256HashString(const std::string& str, void* output, size_t len) { |
16 COMPILE_ASSERT(SHA256_LENGTH == SHA256_DIGEST_LENGTH, | 16 COMPILE_ASSERT(SHA256_LENGTH == SHA256_DIGEST_LENGTH, |
17 API_and_OpenSSL_SHA256_lengths_must_match); | 17 API_and_OpenSSL_SHA256_lengths_must_match); |
18 ScopedOpenSSLSafeSizeBuffer<SHA256_DIGEST_LENGTH> result( | 18 ScopedOpenSSLSafeSizeBuffer<SHA256_DIGEST_LENGTH> result( |
19 reinterpret_cast<unsigned char*>(output), len); | 19 reinterpret_cast<unsigned char*>(output), len); |
20 ::SHA256(reinterpret_cast<const unsigned char*>(str.data()), str.size(), | 20 ::SHA256(reinterpret_cast<const unsigned char*>(str.data()), str.size(), |
21 result.safe_buffer()); | 21 result.safe_buffer()); |
22 } | 22 } |
23 | 23 |
24 std::string SHA256HashString(const std::string& str) { | 24 std::string SHA256HashString(const std::string& str) { |
25 std::string output(SHA256_LENGTH, 0); | 25 std::string output(SHA256_LENGTH, 0); |
26 SHA256HashString(str, string_as_array(&output), output.size()); | 26 SHA256HashString(str, string_as_array(&output), output.size()); |
27 return output; | 27 return output; |
28 } | 28 } |
29 | 29 |
| 30 namespace { |
| 31 |
| 32 class SHA256ContextOpenSSL : public SHA256Context { |
| 33 public: |
| 34 SHA256ContextOpenSSL() { |
| 35 SHA256_Init(&ctx_); |
| 36 } |
| 37 |
| 38 virtual ~SHA256ContextOpenSSL() { |
| 39 OPENSSL_cleanse(&ctx_, sizeof(ctx_)); |
| 40 } |
| 41 |
| 42 virtual void Update(const std::string& str) { |
| 43 SHA256_Update(&ctx_, reinterpret_cast<const unsigned char*>(str.data()), |
| 44 str.size()); |
| 45 } |
| 46 |
| 47 virtual void Finish(void* output, size_t len) { |
| 48 ScopedOpenSSLSafeSizeBuffer<SHA256_DIGEST_LENGTH> result( |
| 49 reinterpret_cast<unsigned char*>(output), len); |
| 50 SHA256_Final(result.safe_buffer(), &ctx_); |
| 51 } |
| 52 |
| 53 private: |
| 54 SHA256_CTX ctx_; |
| 55 }; |
| 56 |
| 57 } // namespace |
| 58 |
| 59 SHA256Context* SHA256Context::Create() { |
| 60 return new SHA256ContextOpenSSL(); |
| 61 } |
| 62 |
30 } // namespace base | 63 } // namespace base |
OLD | NEW |