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.
5 // Utility class for calculating the HMAC for a given message. We currently
6 // only support SHA1 for the hash algorithm, but this can be extended easily.
12 #include "base/basictypes.h"
13 #include "base/compiler_specific.h"
14 #include "base/memory/scoped_ptr.h"
15 #include "base/string_piece.h"
16 #include "crypto/crypto_export.h"
20 // Simplify the interface and reduce includes by abstracting out the internals.
21 struct HMACPlatformData
;
23 class CRYPTO_EXPORT HMAC
{
25 // The set of supported hash functions. Extend as required.
31 explicit HMAC(HashAlgorithm hash_alg
);
34 // Returns the length of digest that this HMAC will create.
35 size_t DigestLength() const;
37 // TODO(abarth): Add a PreferredKeyLength() member function.
39 // Initializes this instance using |key| of the length |key_length|. Call Init
40 // only once. It returns false on the second or later calls.
41 // TODO(abarth): key_length should be a size_t.
42 bool Init(const unsigned char* key
, int key_length
) WARN_UNUSED_RESULT
;
44 // Initializes this instance using |key|. Call Init only once. It returns
45 // false on the second or later calls.
46 bool Init(const base::StringPiece
& key
) WARN_UNUSED_RESULT
{
47 return Init(reinterpret_cast<const unsigned char*>(key
.data()),
48 static_cast<int>(key
.size()));
51 // Calculates the HMAC for the message in |data| using the algorithm supplied
52 // to the constructor and the key supplied to the Init method. The HMAC is
53 // returned in |digest|, which has |digest_length| bytes of storage available.
54 // TODO(abarth): digest_length should be a size_t.
55 bool Sign(const base::StringPiece
& data
, unsigned char* digest
,
56 int digest_length
) const WARN_UNUSED_RESULT
;
58 // Verifies that the HMAC for the message in |data| equals the HMAC provided
59 // in |digest|, using the algorithm supplied to the constructor and the key
60 // supplied to the Init method. Use of this method is strongly recommended
61 // over using Sign() with a manual comparison (such as memcmp), as such
62 // comparisons may result in side-channel disclosures, such as timing, that
63 // undermine the cryptographic integrity. |digest| must be exactly
64 // |DigestLength()| bytes long.
65 bool Verify(const base::StringPiece
& data
,
66 const base::StringPiece
& digest
) const WARN_UNUSED_RESULT
;
68 // Verifies a truncated HMAC, behaving identical to Verify(), except
69 // that |digest| is allowed to be smaller than |DigestLength()|.
71 const base::StringPiece
& data
,
72 const base::StringPiece
& digest
) const WARN_UNUSED_RESULT
;
75 HashAlgorithm hash_alg_
;
76 scoped_ptr
<HMACPlatformData
> plat_
;
78 DISALLOW_COPY_AND_ASSIGN(HMAC
);
83 #endif // CRYPTO_HMAC_H_