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 <CommonCrypto/CommonHMAC.h>
9 #include "base/logging.h"
13 struct HMACPlatformData
{
17 HMAC::HMAC(HashAlgorithm hash_alg
)
18 : hash_alg_(hash_alg
), plat_(new HMACPlatformData()) {
19 // Only SHA-1 and SHA-256 hash algorithms are supported now.
20 DCHECK(hash_alg_
== SHA1
|| hash_alg_
== SHA256
);
23 bool HMAC::Init(const unsigned char *key
, int key_length
) {
24 if (!plat_
->key_
.empty()) {
25 // Init must not be called more than once on the same HMAC object.
30 plat_
->key_
.assign(reinterpret_cast<const char*>(key
), key_length
);
37 plat_
->key_
.assign(plat_
->key_
.length(), std::string::value_type());
39 plat_
->key_
.reserve(0);
42 bool HMAC::Sign(const base::StringPiece
& data
,
43 unsigned char* digest
,
44 int digest_length
) const {
45 if (plat_
->key_
.empty()) {
46 // Init has not been called or has failed.
51 CCHmacAlgorithm algorithm
;
52 int algorithm_digest_length
;
55 algorithm
= kCCHmacAlgSHA1
;
56 algorithm_digest_length
= CC_SHA1_DIGEST_LENGTH
;
59 algorithm
= kCCHmacAlgSHA256
;
60 algorithm_digest_length
= CC_SHA256_DIGEST_LENGTH
;
67 if (digest_length
< algorithm_digest_length
) {
73 plat_
->key_
.data(), plat_
->key_
.length(), data
.data(), data
.length(),