1 /* 2 * Copyright (c) 2024 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 16 #ifndef OHOS_DM_CRYPTO_MGR_H 17 #define OHOS_DM_CRYPTO_MGR_H 18 19 #include <cinttypes> 20 #include <string> 21 #include <mutex> 22 23 namespace OHOS { 24 namespace DistributedHardware { 25 #define SESSION_KEY_LENGTH 32 26 #define GCM_IV_LEN 12 27 28 typedef struct DMSessionKey { 29 uint8_t *key = nullptr; 30 uint32_t keyLen = 0; 31 } DMSessionKey; 32 33 typedef struct AesGcmCipherKey { 34 uint32_t keyLen = 0; 35 unsigned char key[SESSION_KEY_LENGTH] = {0}; 36 unsigned char iv[GCM_IV_LEN] = {0}; 37 } AesGcmCipherKey; 38 39 class CryptoMgr { 40 public: 41 CryptoMgr(); 42 ~CryptoMgr(); 43 int32_t EncryptMessage(const std::string &inputMsg, std::string &outputMsg); 44 int32_t DecryptMessage(const std::string &inputMsg, std::string &outputMsg); 45 int32_t SaveSessionKey(const uint8_t *sessionKey, const uint32_t keyLen); 46 int32_t ProcessSessionKey(const uint8_t *sessionKey, const uint32_t keyLen); 47 void ClearSessionKey(); 48 std::vector<unsigned char> GetSessionKey(); 49 50 private: 51 int32_t DoEncryptData(AesGcmCipherKey *cipherKey, const unsigned char *input, uint32_t inLen, 52 unsigned char *encryptData, uint32_t *encryptLen); 53 int32_t GenerateRandomArray(unsigned char *randStr, uint32_t len); 54 int32_t MbedAesGcmEncrypt(const AesGcmCipherKey *cipherKey, const unsigned char *plainText, 55 uint32_t plainTextSize, unsigned char *cipherText, uint32_t cipherTextLen); 56 57 int32_t DoDecryptData(AesGcmCipherKey *cipherKey, const unsigned char *input, uint32_t inLen, 58 unsigned char *decryptData, uint32_t *decryptLen); 59 int32_t MbedAesGcmDecrypt(const AesGcmCipherKey *cipherKey, const unsigned char *cipherText, 60 uint32_t cipherTextSize, unsigned char *plain, uint32_t &plainLen); 61 private: 62 std::mutex sessionKeyMtx_; 63 DMSessionKey sessionKey_; 64 std::mutex randomLock_; 65 }; 66 } // namespace DistributedHardware 67 } // namespace OHOS 68 #endif // OHOS_DM_CRYPTO_MGR_H