1 // Copyright (c) 2011 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/hmac.h"
6
7 #include <openssl/hmac.h>
8 #include <stddef.h>
9
10 #include <algorithm>
11 #include <vector>
12
13 #include "base/logging.h"
14 #include "base/memory/scoped_ptr.h"
15 #include "base/stl_util.h"
16 #include "crypto/openssl_util.h"
17
18 namespace crypto {
19
20 struct HMACPlatformData {
21 std::vector<unsigned char> key;
22 };
23
HMAC(HashAlgorithm hash_alg)24 HMAC::HMAC(HashAlgorithm hash_alg) : hash_alg_(hash_alg) {
25 // Only SHA-1 and SHA-256 hash algorithms are supported now.
26 DCHECK(hash_alg_ == SHA1 || hash_alg_ == SHA256);
27 }
28
Init(const unsigned char * key,size_t key_length)29 bool HMAC::Init(const unsigned char* key, size_t key_length) {
30 // Init must not be called more than once on the same HMAC object.
31 DCHECK(!plat_);
32 plat_.reset(new HMACPlatformData());
33 plat_->key.assign(key, key + key_length);
34 return true;
35 }
36
~HMAC()37 HMAC::~HMAC() {
38 if (plat_) {
39 // Zero out key copy.
40 plat_->key.assign(plat_->key.size(), 0);
41 STLClearObject(&plat_->key);
42 }
43 }
44
Sign(const base::StringPiece & data,unsigned char * digest,size_t digest_length) const45 bool HMAC::Sign(const base::StringPiece& data,
46 unsigned char* digest,
47 size_t digest_length) const {
48 DCHECK(plat_); // Init must be called before Sign.
49
50 ScopedOpenSSLSafeSizeBuffer<EVP_MAX_MD_SIZE> result(digest, digest_length);
51 return !!::HMAC(hash_alg_ == SHA1 ? EVP_sha1() : EVP_sha256(),
52 plat_->key.data(), plat_->key.size(),
53 reinterpret_cast<const unsigned char*>(data.data()),
54 data.size(), result.safe_buffer(), NULL);
55 }
56
57 } // namespace crypto
58