1 /* 2 * Copyright (c) 2021 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 #ifndef STORAGE_DAEMON_CRYPTO_BASEKEY_H 16 #define STORAGE_DAEMON_CRYPTO_BASEKEY_H 17 18 #include <string> 19 20 #include "key_blob.h" 21 22 namespace OHOS { 23 namespace StorageDaemon { 24 const uint8_t RETRIEVE_KEY = 0x0; 25 const uint8_t FIRST_CREATE_KEY = 0x6c; 26 const uint8_t USER_LOGOUT = 0x0; 27 const uint8_t USER_DESTROY = 0x1; 28 29 class BaseKey { 30 public: 31 BaseKey() = delete; 32 BaseKey(const std::string &dir, uint8_t keyLen = CRYPTO_AES_256_XTS_KEY_SIZE); 33 ~BaseKey() = default; 34 35 /* key operations */ 36 bool InitKey(); 37 bool StoreKey(const UserAuth &auth); 38 bool UpdateKey(const std::string &keypath = ""); 39 bool RestoreKey(const UserAuth &auth); 40 virtual bool ActiveKey(uint32_t flag, const std::string &mnt = MNT_DATA) = 0; 41 virtual bool InactiveKey(uint32_t flag, const std::string &mnt = MNT_DATA) = 0; 42 bool ClearKey(const std::string &mnt = MNT_DATA); 43 bool UpgradeKeys(); 44 45 KeyInfo keyInfo_; GetDir()46 std::string GetDir() const 47 { 48 return dir_; 49 } 50 51 protected: 52 static bool SaveKeyBlob(const KeyBlob &blob, const std::string &path); 53 std::string dir_ {}; 54 55 private: 56 bool DoStoreKey(const UserAuth &auth); 57 bool DoRestoreKey(const UserAuth &auth, const std::string &keypath); 58 static bool GenerateAndSaveKeyBlob(KeyBlob &blob, const std::string &path, const uint32_t size); 59 static bool GenerateKeyBlob(KeyBlob &blob, const uint32_t size); 60 static bool LoadKeyBlob(KeyBlob &blob, const std::string &path, const uint32_t size); 61 bool Encrypt(const UserAuth &auth); 62 bool Decrypt(const UserAuth &auth); 63 int GetCandidateVersion() const; 64 std::string GetCandidateDir() const; 65 std::string GetNextCandidateDir() const; 66 void SyncKeyDir() const; 67 68 KeyContext keyContext_ {}; 69 uint8_t keyLen_ {}; 70 }; 71 } // namespace StorageDaemon 72 } // namespace OHOS 73 74 #endif // STORAGE_DAEMON_CRYPTO_BASEKEY_H 75