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 49 private: 50 int32_t DoEncryptData(AesGcmCipherKey *cipherKey, const unsigned char *input, uint32_t inLen, 51 unsigned char *encryptData, uint32_t *encryptLen); 52 int32_t GenerateRandomArray(unsigned char *randStr, uint32_t len); 53 int32_t MbedAesGcmEncrypt(const AesGcmCipherKey *cipherKey, const unsigned char *plainText, 54 uint32_t plainTextSize, unsigned char *cipherText, uint32_t cipherTextLen); 55 56 int32_t DoDecryptData(AesGcmCipherKey *cipherKey, const unsigned char *input, uint32_t inLen, 57 unsigned char *decryptData, uint32_t *decryptLen); 58 int32_t MbedAesGcmDecrypt(const AesGcmCipherKey *cipherKey, const unsigned char *cipherText, 59 uint32_t cipherTextSize, unsigned char *plain, uint32_t plainLen); 60 private: 61 std::mutex sessionKeyMtx_; 62 DMSessionKey sessionKey_; 63 std::mutex randomLock_; 64 }; 65 } // namespace DistributedHardware 66 } // namespace OHOS 67 #endif // OHOS_DM_CRYPTO_MGR_H