• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #ifndef ANDROID_FRAMEWORKS_ML_NN_COMMON_TOKEN_HASHER_H
18 #define ANDROID_FRAMEWORKS_ML_NN_COMMON_TOKEN_HASHER_H
19 
20 #include <android-base/macros.h>
21 #include <openssl/sha.h>
22 
23 #include <cstring>
24 #include <vector>
25 
26 namespace android {
27 namespace nn {
28 
29 class TokenHasher {
30     DISALLOW_COPY_AND_ASSIGN(TokenHasher);
31 
32    public:
33     // Initializes the hasher with token. If token is nullptr, the hasher is set to be empty;
34     // otherwise, it must be of length ANEURALNETWORKS_BYTE_SIZE_OF_CACHE_TOKEN.
35     TokenHasher(const uint8_t* token);
36 
37     // Updates with a byte array. Returns false and sets to be empty on fail.
38     // The client must check if the hasher is valid before invoking this method.
39     bool update(const void* bytes, size_t length);
40 
41     // Updates with a string ended with '\0'. Returns false and sets to be empty on fail.
42     // The client must check if the hasher is valid before invoking this method.
updateFromString(const char * s)43     bool updateFromString(const char* s) { return update(s, strlen(s)); }
44 
45     // Finishes the hasher, and writes re-hashed token to mToken.
46     // Returns false and sets to be empty on fail.
47     // The client must check if the hasher is valid before invoking this method.
48     bool finish();
49 
50     // Returns a pointer to the transformed token if the hasher is successfully finished.
51     // Returns nullptr if the hasher is initialized with a nullptr, or some call on the
52     // hasher failed.
53     // Aborts if the hasher is valid but finish has not been called.
54     const uint8_t* getCacheToken() const;
55 
ok()56     bool ok() const { return !mIsError; }
57 
58    private:
59     // Stores the transformed token, non-empty iff the hasher is not initialized
60     // with nullptr and finish is called.
61     std::vector<uint8_t> mToken;
62     SHA256_CTX mHasher;
63     // Indicates that either the hasher is initialized with a nullptr, or some call on
64     // the hasher failed.
65     bool mIsError;
66 };
67 
68 }  // namespace nn
69 }  // namespace android
70 
71 #endif  // ANDROID_FRAMEWORKS_ML_NN_COMMON_TOKEN_HASHER_H
72