1 /*
2  * Copyright (C) 2019 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 #define LOG_TAG "TokenHasher"
18 
19 #include "TokenHasher.h"
20 
21 #include "NeuralNetworks.h"
22 
23 #include <android-base/logging.h>
24 #include <openssl/sha.h>
25 
26 namespace android {
27 namespace nn {
28 
TokenHasher(const uint8_t * token)29 TokenHasher::TokenHasher(const uint8_t* token) : mIsError(token == nullptr) {
30     if (mIsError) {
31         return;
32     }
33     if (SHA256_Init(&mHasher) == 0 ||
34         SHA256_Update(&mHasher, token, ANEURALNETWORKS_BYTE_SIZE_OF_CACHE_TOKEN) == 0) {
35         mIsError = true;
36     }
37 }
38 
update(const void * bytes,size_t length)39 bool TokenHasher::update(const void* bytes, size_t length) {
40     CHECK(!mIsError) << "Calling update on an token in error state";
41     if (SHA256_Update(&mHasher, bytes, length) == 0) {
42         mIsError = true;
43         return false;
44     }
45     return true;
46 }
47 
finish()48 bool TokenHasher::finish() {
49     CHECK(!mIsError) << "Calling finish on an token in error state";
50     static_assert(SHA256_DIGEST_LENGTH == ANEURALNETWORKS_BYTE_SIZE_OF_CACHE_TOKEN,
51                   "SHA256_DIGEST_LENGTH != ANEURALNETWORKS_BYTE_SIZE_OF_CACHE_TOKEN");
52     mToken.resize(ANEURALNETWORKS_BYTE_SIZE_OF_CACHE_TOKEN);
53     if (SHA256_Final(mToken.data(), &mHasher) == 0) {
54         mToken.clear();
55         mIsError = true;
56         return false;
57     }
58     return true;
59 }
60 
getCacheToken() const61 const uint8_t* TokenHasher::getCacheToken() const {
62     if (mIsError) {
63         return nullptr;
64     } else {
65         CHECK(!mToken.empty());
66         return mToken.data();
67     }
68 }
69 
70 }  // namespace nn
71 }  // namespace android
72