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/hmac.h"
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"
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);
28 key_.assign(key_.size(), 0);
29 base::STLClearObject(&key_);
32 size_t HMAC::DigestLength() const {
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_);
48 key_.assign(key, key + key_length);
52 bool HMAC::Init(const SymmetricKey* key) {
53 return Init(key->key());
56 bool HMAC::Sign(base::StringPiece data,
57 unsigned char* digest,
58 size_t digest_length) const {
61 ScopedOpenSSLSafeSizeBuffer<EVP_MAX_MD_SIZE> result(digest, digest_length);
62 return !!::HMAC(hash_alg_ == SHA1 ? EVP_sha1() : EVP_sha256(), key_.data(),
64 reinterpret_cast<const unsigned char*>(data.data()),
65 data.size(), result.safe_buffer(), nullptr);
68 bool HMAC::Verify(base::StringPiece data, base::StringPiece digest) const {
69 if (digest.size() != DigestLength())
71 return VerifyTruncated(data, digest);
74 bool HMAC::VerifyTruncated(base::StringPiece data,
75 base::StringPiece digest) const {
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))
84 return SecureMemEqual(digest.data(), computed_digest.get(),
85 std::min(digest.size(), digest_length));