blob: 16201052a1c934853a32cad176c1cc8f7e1d40bc [file] [log] [blame]
Shawn Willden0d560bf2014-12-15 17:44:02 -07001/*
2 * Copyright 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "hmac_operation.h"
18
19#include <openssl/evp.h>
20#include <openssl/hmac.h>
21
22namespace keymaster {
23
24HmacOperation::HmacOperation(keymaster_purpose_t purpose, const Logger& logger,
25 const uint8_t* key_data, size_t key_data_size,
26 keymaster_digest_t digest, size_t tag_length)
27 : Operation(purpose, logger), error_(KM_ERROR_OK), tag_length_(tag_length) {
28 // Initialize CTX first, so dtor won't crash even if we error out later.
29 HMAC_CTX_init(&ctx_);
30
31 const EVP_MD* md;
32 switch (digest) {
33 case KM_DIGEST_SHA_2_256:
34 md = EVP_sha256();
35 break;
36 default:
37 error_ = KM_ERROR_UNSUPPORTED_DIGEST;
38 return;
39 }
40
41 if ((int)tag_length_ > EVP_MD_size(md)) {
42 error_ = KM_ERROR_UNSUPPORTED_MAC_LENGTH;
43 return;
44 }
45
46 HMAC_Init_ex(&ctx_, key_data, key_data_size, md, NULL /* engine */);
47}
48
49HmacOperation::~HmacOperation() {
50 HMAC_CTX_cleanup(&ctx_);
51}
52
53keymaster_error_t HmacOperation::Begin() {
54 return error_;
55}
56
57keymaster_error_t HmacOperation::Update(const Buffer& input, Buffer* /* output */,
58 size_t* input_consumed) {
59 if (!HMAC_Update(&ctx_, input.peek_read(), input.available_read()))
60 return KM_ERROR_UNKNOWN_ERROR;
61 *input_consumed = input.available_read();
62 return KM_ERROR_OK;
63}
64
65keymaster_error_t HmacOperation::Abort() {
66 return KM_ERROR_OK;
67}
68
69keymaster_error_t HmacOperation::Finish(const Buffer& signature, Buffer* output) {
70 uint8_t digest[EVP_MAX_MD_SIZE];
71 unsigned int digest_len;
72 if (!HMAC_Final(&ctx_, digest, &digest_len))
73 return KM_ERROR_UNKNOWN_ERROR;
74
75 switch (purpose()) {
76 case KM_PURPOSE_SIGN:
77 output->reserve(tag_length_);
78 output->write(digest, tag_length_);
79 return KM_ERROR_OK;
80 case KM_PURPOSE_VERIFY:
81 if (signature.available_read() != tag_length_)
82 return KM_ERROR_INVALID_INPUT_LENGTH;
83 if (memcmp(signature.peek_read(), digest, tag_length_) != 0)
84 return KM_ERROR_VERIFICATION_FAILED;
85 return KM_ERROR_OK;
86 default:
87 return KM_ERROR_UNSUPPORTED_PURPOSE;
88 }
89}
90
91} // namespace keymaster