blob: 93b3d9e96b5ab87c72dfe752507d77f218e2a507 [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#include <openssl/bio.h>
6#include <openssl/buffer.h>
7#include <openssl/evp.h>
adlr@google.comc98a7ed2009-12-04 18:54:03 +00008#include "chromeos/obsolete_logging.h"
rspangler@google.com49fdf182009-10-10 00:57:34 +00009#include "update_engine/omaha_hash_calculator.h"
10
11namespace chromeos_update_engine {
12
13OmahaHashCalculator::OmahaHashCalculator() {
adlr@google.comc98a7ed2009-12-04 18:54:03 +000014 CHECK_EQ(SHA1_Init(&ctx_), 1);
rspangler@google.com49fdf182009-10-10 00:57:34 +000015}
16
17// Update is called with all of the data that should be hashed in order.
18// Mostly just passes the data through to OpenSSL's SHA1_Update()
19void OmahaHashCalculator::Update(const char* data, size_t length) {
20 CHECK(hash_.empty()) << "Can't Update after hash is finalized";
21 COMPILE_ASSERT(sizeof(size_t) <= sizeof(unsigned long),
22 length_param_may_be_truncated_in_SHA1_Update);
adlr@google.comc98a7ed2009-12-04 18:54:03 +000023 CHECK_EQ(SHA1_Update(&ctx_, data, length), 1);
rspangler@google.com49fdf182009-10-10 00:57:34 +000024}
25
26// Call Finalize() when all data has been passed in. This mostly just
27// calls OpenSSL's SHA1_Final() and then base64 encodes the hash.
28void OmahaHashCalculator::Finalize() {
29 CHECK(hash_.empty()) << "Don't call Finalize() twice";
30 unsigned char md[SHA_DIGEST_LENGTH];
adlr@google.comc98a7ed2009-12-04 18:54:03 +000031 CHECK_EQ(SHA1_Final(md, &ctx_), 1);
rspangler@google.com49fdf182009-10-10 00:57:34 +000032
33 // Convert md to base64 encoding and store it in hash_
34 BIO *b64 = BIO_new(BIO_f_base64());
35 CHECK(b64);
36 BIO *bmem = BIO_new(BIO_s_mem());
37 CHECK(bmem);
38 b64 = BIO_push(b64, bmem);
adlr@google.comc98a7ed2009-12-04 18:54:03 +000039 CHECK_EQ(BIO_write(b64, md, sizeof(md)), sizeof(md));
40 CHECK_EQ(BIO_flush(b64), 1);
rspangler@google.com49fdf182009-10-10 00:57:34 +000041
42 BUF_MEM *bptr = NULL;
43 BIO_get_mem_ptr(b64, &bptr);
44 hash_.assign(bptr->data, bptr->length - 1);
45
46 BIO_free_all(b64);
47}
48
49std::string OmahaHashCalculator::OmahaHashOfBytes(
50 const void* data, size_t length) {
51 OmahaHashCalculator calc;
52 calc.Update(reinterpret_cast<const char*>(data), length);
53 calc.Finalize();
54 return calc.hash();
55}
56
57std::string OmahaHashCalculator::OmahaHashOfString(
58 const std::string& str) {
59 return OmahaHashOfBytes(str.data(), str.size());
60}
61
62std::string OmahaHashCalculator::OmahaHashOfData(
63 const std::vector<char>& data) {
64 return OmahaHashOfBytes(&data[0], data.size());
65}
66
67} // namespace chromeos_update_engine