blob: 28602a3829d9daa7b87ae0fb6723e1b67bb20383 [file] [log] [blame]
rspangler@google.com49fdf182009-10-10 00:57:34 +00001// Copyright (c) 2009 The Chromium OS 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#ifndef UPDATE_ENGINE_OMAHA_HASH_CALCULATOR_H__
6#define UPDATE_ENGINE_OMAHA_HASH_CALCULATOR_H__
7
8#include "base/basictypes.h"
9#include <string>
10#include <openssl/sha.h>
11
12// Omaha uses base64 encoded SHA-1 as the hash. This class provides a simple
13// wrapper around OpenSSL providing such a formatted hash of data passed in.
14// The methods of this class must be called in a very specific order:
15// First the ctor (of course), then 0 or more calls to Update(), then
16// Finalize(), then 0 or more calls to hash().
17
18namespace chromeos_update_engine {
19
20class OmahaHashCalculator {
21 public:
22 OmahaHashCalculator();
23
24 // Update is called with all of the data that should be hashed in order.
25 // Update will read |length| bytes of |data|
26 void Update(const char* data, size_t length);
27
28 // Call Finalize() when all data has been passed in. This method tells
29 // OpenSSl that no more data will come in and base64 encodes the resulting
30 // hash.
31 void Finalize();
32
33 // Gets the hash. Finalize() must have been called.
34 const std::string& hash() const {
35 CHECK(!hash_.empty()) << "Call Finalize() first";
36 return hash_;
37 }
38
39 // Used by tests
40 static std::string OmahaHashOfBytes(const void* data, size_t length);
41 static std::string OmahaHashOfString(const std::string& str);
42 static std::string OmahaHashOfData(const std::vector<char>& data);
43
44 private:
45 // If non-empty, the final base64 encoded hash. Will only be set to
46 // non-empty when Finalize is called.
47 std::string hash_;
48
49 // The hash state used by OpenSSL
50 SHA_CTX ctx_;
51 DISALLOW_COPY_AND_ASSIGN(OmahaHashCalculator);
52};
53
54} // namespace chromeos_update_engine
55
56#endif // UPDATE_ENGINE_OMAHA_HASH_CALCULATOR_H__