1 // Copyright 2012 The Chromium Authors
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/check.h"
13 #include "base/check_op.h"
14 #include "base/notreached.h"
15 #include "base/stl_util.h"
16 #include "crypto/openssl_util.h"
17 #include "crypto/secure_util.h"
18 #include "crypto/symmetric_key.h"
19 #include "third_party/boringssl/src/include/openssl/hmac.h"
23 HMAC::HMAC(HashAlgorithm hash_alg) : hash_alg_(hash_alg), initialized_(false) {
24 // Only SHA-1 and SHA-256 hash algorithms are supported now.
25 DCHECK(hash_alg_ == SHA1 || hash_alg_ == SHA256);
30 key_.assign(key_.size(), 0);
31 base::STLClearObject(&key_);
34 size_t HMAC::DigestLength() const {
46 bool HMAC::Init(const unsigned char* key, size_t key_length) {
47 // Init must not be called more than once on the same HMAC object.
48 DCHECK(!initialized_);
50 key_.assign(key, key + key_length);
54 bool HMAC::Init(const SymmetricKey* key) {
55 return Init(key->key());
58 bool HMAC::Sign(std::string_view data,
59 unsigned char* digest,
60 size_t digest_length) const {
61 return Sign(base::as_bytes(base::make_span(data)),
62 base::make_span(digest, digest_length));
65 bool HMAC::Sign(base::span<const uint8_t> data,
66 base::span<uint8_t> digest) const {
69 if (digest.size() > DigestLength())
72 ScopedOpenSSLSafeSizeBuffer<EVP_MAX_MD_SIZE> result(digest.data(),
74 return !!::HMAC(hash_alg_ == SHA1 ? EVP_sha1() : EVP_sha256(), key_.data(),
75 key_.size(), data.data(), data.size(), result.safe_buffer(),
79 bool HMAC::Verify(std::string_view data, std::string_view digest) const {
80 return Verify(base::as_bytes(base::make_span(data)),
81 base::as_bytes(base::make_span(digest)));
84 bool HMAC::Verify(base::span<const uint8_t> data,
85 base::span<const uint8_t> digest) const {
86 if (digest.size() != DigestLength())
88 return VerifyTruncated(data, digest);
91 bool HMAC::VerifyTruncated(std::string_view data,
92 std::string_view digest) const {
93 return VerifyTruncated(base::as_bytes(base::make_span(data)),
94 base::as_bytes(base::make_span(digest)));
97 bool HMAC::VerifyTruncated(base::span<const uint8_t> data,
98 base::span<const uint8_t> digest) const {
102 size_t digest_length = DigestLength();
103 if (digest.size() > digest_length)
106 uint8_t computed_digest[EVP_MAX_MD_SIZE];
107 CHECK_LE(digest.size(), size_t{EVP_MAX_MD_SIZE});
108 if (!Sign(data, base::make_span(computed_digest, digest.size())))
111 return SecureMemEqual(digest.data(), computed_digest, digest.size());
114 } // namespace crypto