ash: Update app list layout:
[chromium-blink-merge.git] / crypto / secure_hash_openssl.cc
bloba542e225770cdbadedb569e43c6ba116e1ccd034
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.
5 #include "crypto/secure_hash.h"
7 #include <openssl/ssl.h>
9 #include "base/basictypes.h"
10 #include "base/logging.h"
11 #include "base/pickle.h"
12 #include "crypto/openssl_util.h"
14 namespace crypto {
16 namespace {
18 const char kSHA256Descriptor[] = "OpenSSL";
20 class SecureHashSHA256OpenSSL : public SecureHash {
21 public:
22 static const int kSecureHashVersion = 1;
24 SecureHashSHA256OpenSSL() {
25 SHA256_Init(&ctx_);
28 virtual ~SecureHashSHA256OpenSSL() {
29 OPENSSL_cleanse(&ctx_, sizeof(ctx_));
32 virtual void Update(const void* input, size_t len) {
33 SHA256_Update(&ctx_, static_cast<const unsigned char*>(input), len);
36 virtual void Finish(void* output, size_t len) {
37 ScopedOpenSSLSafeSizeBuffer<SHA256_DIGEST_LENGTH> result(
38 static_cast<unsigned char*>(output), len);
39 SHA256_Final(result.safe_buffer(), &ctx_);
42 virtual bool Serialize(Pickle* pickle);
43 virtual bool Deserialize(PickleIterator* data_iterator);
45 private:
46 SHA256_CTX ctx_;
49 bool SecureHashSHA256OpenSSL::Serialize(Pickle* pickle) {
50 if (!pickle)
51 return false;
53 if (!pickle->WriteInt(kSecureHashVersion) ||
54 !pickle->WriteString(kSHA256Descriptor) ||
55 !pickle->WriteBytes(&ctx_, sizeof(ctx_))) {
56 return false;
59 return true;
62 bool SecureHashSHA256OpenSSL::Deserialize(PickleIterator* data_iterator) {
63 if (!data_iterator)
64 return false;
66 int version;
67 if (!data_iterator->ReadInt(&version))
68 return false;
70 if (version > kSecureHashVersion)
71 return false; // We don't know how to deal with this.
73 std::string type;
74 if (!data_iterator->ReadString(&type))
75 return false;
77 if (type != kSHA256Descriptor)
78 return false; // It's the wrong kind.
80 const char* data = NULL;
81 if (!data_iterator->ReadBytes(&data, sizeof(ctx_)))
82 return false;
84 memcpy(&ctx_, data, sizeof(ctx_));
86 return true;
89 } // namespace
91 SecureHash* SecureHash::Create(Algorithm algorithm) {
92 switch (algorithm) {
93 case SHA256:
94 return new SecureHashSHA256OpenSSL();
95 default:
96 NOTIMPLEMENTED();
97 return NULL;
101 } // namespace crypto