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.
4
5 #include "crypto/hmac.h"
6
7 #include <stddef.h>
8
9 #include <algorithm>
10 #include <string>
11
12 #include "base/logging.h"
13 #include "base/stl_util.h"
14 #include "crypto/openssl_util.h"
15 #include "crypto/secure_util.h"
16 #include "crypto/symmetric_key.h"
17 #include "third_party/boringssl/src/include/openssl/hmac.h"
18
19 namespace crypto {
20
HMAC(HashAlgorithm hash_alg)21 HMAC::HMAC(HashAlgorithm hash_alg) : hash_alg_(hash_alg), initialized_(false) {
22 // Only SHA-1 and SHA-256 hash algorithms are supported now.
23 DCHECK(hash_alg_ == SHA1 || hash_alg_ == SHA256);
24 }
25
~HMAC()26 HMAC::~HMAC() {
27 // Zero out key copy.
28 key_.assign(key_.size(), 0);
29 base::STLClearObject(&key_);
30 }
31
DigestLength() const32 size_t HMAC::DigestLength() const {
33 switch (hash_alg_) {
34 case SHA1:
35 return 20;
36 case SHA256:
37 return 32;
38 default:
39 NOTREACHED();
40 return 0;
41 }
42 }
43
Init(const unsigned char * key,size_t key_length)44 bool HMAC::Init(const unsigned char* key, size_t key_length) {
45 // Init must not be called more than once on the same HMAC object.
46 DCHECK(!initialized_);
47 initialized_ = true;
48 key_.assign(key, key + key_length);
49 return true;
50 }
51
Init(const SymmetricKey * key)52 bool HMAC::Init(const SymmetricKey* key) {
53 return Init(key->key());
54 }
55
Sign(base::StringPiece data,unsigned char * digest,size_t digest_length) const56 bool HMAC::Sign(base::StringPiece data,
57 unsigned char* digest,
58 size_t digest_length) const {
59 DCHECK(initialized_);
60
61 ScopedOpenSSLSafeSizeBuffer<EVP_MAX_MD_SIZE> result(digest, digest_length);
62 return !!::HMAC(hash_alg_ == SHA1 ? EVP_sha1() : EVP_sha256(), key_.data(),
63 key_.size(),
64 reinterpret_cast<const unsigned char*>(data.data()),
65 data.size(), result.safe_buffer(), nullptr);
66 }
67
Verify(base::StringPiece data,base::StringPiece digest) const68 bool HMAC::Verify(base::StringPiece data, base::StringPiece digest) const {
69 if (digest.size() != DigestLength())
70 return false;
71 return VerifyTruncated(data, digest);
72 }
73
VerifyTruncated(base::StringPiece data,base::StringPiece digest) const74 bool HMAC::VerifyTruncated(base::StringPiece data,
75 base::StringPiece digest) const {
76 if (digest.empty())
77 return false;
78 size_t digest_length = DigestLength();
79 std::unique_ptr<unsigned char[]> computed_digest(
80 new unsigned char[digest_length]);
81 if (!Sign(data, computed_digest.get(), digest_length))
82 return false;
83
84 return SecureMemEqual(digest.data(), computed_digest.get(),
85 std::min(digest.size(), digest_length));
86 }
87
88 } // namespace crypto
89