Rename base::FieldTrialList::RegistrationList --> RegistrationMap.
[chromium-blink-merge.git] / crypto / hmac_openssl.cc
blobf7010c81bc651a562996b788645352b6cb2a3e1b
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 #include "crypto/hmac.h"
7 #include <openssl/hmac.h>
9 #include <algorithm>
10 #include <vector>
12 #include "base/logging.h"
13 #include "base/memory/scoped_ptr.h"
14 #include "base/stl_util.h"
15 #include "crypto/openssl_util.h"
17 namespace crypto {
19 struct HMACPlatformData {
20 std::vector<unsigned char> key;
23 HMAC::HMAC(HashAlgorithm hash_alg)
24 : hash_alg_(hash_alg), plat_(new HMACPlatformData()) {
25 // Only SHA-1 and SHA-256 hash algorithms are supported now.
26 DCHECK(hash_alg_ == SHA1 || hash_alg_ == SHA256);
29 bool HMAC::Init(const unsigned char* key, size_t key_length) {
30 // Init must not be called more than once on the same HMAC object.
31 DCHECK(plat_->key.empty());
33 plat_->key.assign(key, key + key_length);
34 return true;
37 HMAC::~HMAC() {
38 // Zero out key copy.
39 plat_->key.assign(plat_->key.size(), 0);
40 STLClearObject(&plat_->key);
43 bool HMAC::Sign(const base::StringPiece& data,
44 unsigned char* digest,
45 size_t digest_length) const {
46 DCHECK(!plat_->key.empty()); // Init must be called before Sign.
48 ScopedOpenSSLSafeSizeBuffer<EVP_MAX_MD_SIZE> result(digest, digest_length);
49 return ::HMAC(hash_alg_ == SHA1 ? EVP_sha1() : EVP_sha256(),
50 &plat_->key[0], plat_->key.size(),
51 reinterpret_cast<const unsigned char*>(data.data()),
52 data.size(),
53 result.safe_buffer(), NULL);
56 } // namespace crypto