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 // 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. 7 8 #ifndef CRYPTO_HMAC_H_ 9 #define CRYPTO_HMAC_H_ 10 #pragma once 11 12 #include <string> 13 14 #include "base/basictypes.h" 15 #include "base/memory/scoped_ptr.h" 16 17 namespace crypto { 18 19 // Simplify the interface and reduce includes by abstracting out the internals. 20 struct HMACPlatformData; 21 22 class HMAC { 23 public: 24 // The set of supported hash functions. Extend as required. 25 enum HashAlgorithm { 26 SHA1, 27 SHA256, 28 }; 29 30 explicit HMAC(HashAlgorithm hash_alg); 31 ~HMAC(); 32 33 // Initializes this instance using |key| of the length |key_length|. Call Init 34 // only once. It returns false on the second or later calls. 35 bool Init(const unsigned char* key, int key_length); 36 37 // Initializes this instance using |key|. Call Init only once. It returns 38 // false on the second or later calls. Init(const std::string & key)39 bool Init(const std::string& key) { 40 return Init(reinterpret_cast<const unsigned char*>(key.data()), 41 static_cast<int>(key.size())); 42 } 43 44 // Calculates the HMAC for the message in |data| using the algorithm supplied 45 // to the constructor and the key supplied to the Init method. The HMAC is 46 // returned in |digest|, which has |digest_length| bytes of storage available. 47 bool Sign(const std::string& data, unsigned char* digest, int digest_length); 48 49 // TODO(albertb): Add a Verify method. 50 51 private: 52 HashAlgorithm hash_alg_; 53 scoped_ptr<HMACPlatformData> plat_; 54 55 DISALLOW_COPY_AND_ASSIGN(HMAC); 56 }; 57 58 } // namespace crypto 59 60 #endif // CRYPTO_HMAC_H_ 61