TokenHasher.cpp 2.0 KB

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