blob: b15f143014cedf09c06df5ad5071c0bb8ab70898 [file] [log] [blame]
chaviw09c8d2d2020-08-24 15:48:26 -07001/*
2 * Copyright (C) 2020 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 <attestation/HmacKeyManager.h>
18#include <log/log.h>
19#include <openssl/hmac.h>
20#include <openssl/rand.h>
21
22namespace android {
23
24static std::array<uint8_t, 128> getRandomKey() {
25 std::array<uint8_t, 128> key;
26 if (RAND_bytes(key.data(), key.size()) != 1) {
27 LOG_ALWAYS_FATAL("Can't generate HMAC key");
28 }
29 return key;
30}
31
32HmacKeyManager::HmacKeyManager() : mHmacKey(getRandomKey()) {}
33
34std::array<uint8_t, 32> HmacKeyManager::sign(const uint8_t* data, size_t size) const {
35 // SHA256 always generates 32-bytes result
36 std::array<uint8_t, 32> hash;
37 unsigned int hashLen = 0;
38 uint8_t* result =
39 HMAC(EVP_sha256(), mHmacKey.data(), mHmacKey.size(), data, size, hash.data(), &hashLen);
40 if (result == nullptr) {
41 ALOGE("Could not sign the data using HMAC");
42 return INVALID_HMAC;
43 }
44
45 if (hashLen != hash.size()) {
46 ALOGE("HMAC-SHA256 has unexpected length");
47 return INVALID_HMAC;
48 }
49
50 return hash;
51}
52} // namespace android