blob: 8b7b96d69b7a428ee267826b8fe10a080a19a1e5 [file] [log] [blame]
[email protected]3b63f8f42011-03-28 01:54:151// Copyright (c) 2011 The Chromium Authors. All rights reserved.
[email protected]70372d42010-10-22 13:12:342// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
[email protected]4b559b4d2011-04-14 17:37:145#include "crypto/hmac.h"
[email protected]70372d42010-10-22 13:12:346
7#include <openssl/hmac.h>
8
9#include <algorithm>
10#include <vector>
11
12#include "base/logging.h"
[email protected]3b63f8f42011-03-28 01:54:1513#include "base/memory/scoped_ptr.h"
[email protected]70372d42010-10-22 13:12:3414#include "base/stl_util-inl.h"
[email protected]4b559b4d2011-04-14 17:37:1415#include "crypto/openssl_util.h"
[email protected]70372d42010-10-22 13:12:3416
[email protected]4b559b4d2011-04-14 17:37:1417namespace crypto {
[email protected]70372d42010-10-22 13:12:3418
19struct HMACPlatformData {
20 std::vector<unsigned char> key;
21};
22
23HMAC::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);
27}
28
29bool HMAC::Init(const unsigned char* key, int key_length) {
30 // Init must not be called more than once on the same HMAC object.
31 DCHECK(plat_->key.empty());
32
33 plat_->key.assign(key, key + key_length);
34 return true;
35}
36
37HMAC::~HMAC() {
38 // Zero out key copy.
39 plat_->key.assign(plat_->key.size(), 0);
40 STLClearObject(&plat_->key);
41}
42
43bool HMAC::Sign(const std::string& data,
44 unsigned char* digest,
[email protected]c6e584c2011-05-18 11:58:4445 int digest_length) const {
[email protected]70372d42010-10-22 13:12:3446 DCHECK_GE(digest_length, 0);
47 DCHECK(!plat_->key.empty()); // Init must be called before Sign.
48
49 ScopedOpenSSLSafeSizeBuffer<EVP_MAX_MD_SIZE> result(digest, digest_length);
50 return ::HMAC(hash_alg_ == SHA1 ? EVP_sha1() : EVP_sha256(),
51 &plat_->key[0], plat_->key.size(),
52 reinterpret_cast<const unsigned char*>(data.data()),
53 data.size(),
54 result.safe_buffer(), NULL);
55}
56
[email protected]4b559b4d2011-04-14 17:37:1457} // namespace crypto