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