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 16 #ifndef NSTACKX_MBEDTLS_H 17 #define NSTACKX_MBEDTLS_H 18 19 #ifdef MBEDTLS_INCLUDED 20 #include "nstackx_common_header.h" 21 22 #include "mbedtls/gcm.h" 23 #include "mbedtls/ctr_drbg.h" 24 #include "mbedtls/entropy.h" 25 #include "mbedtls/chachapoly.h" 26 #include "mbedtls/version.h" 27 #ifdef __cplusplus 28 extern "C" { 29 #endif 30 31 typedef enum { 32 CIPHER_AES_GCM = 0, 33 CIPHER_CHACHA, 34 } DFileCipherType; 35 36 #define AES_128_KEY_LENGTH 16 37 #define AES_192_KEY_LENGTH 24 38 #define AES_256_KEY_LENGTH 32 39 #define GCM_IV_LENGTH 12 40 #define GCM_MAX_AAD_LENGTH 64 41 #define GCM_TAG_LENGTH 16 42 #define GCM_ADDED_LEN (GCM_IV_LENGTH + GCM_TAG_LENGTH) 43 #define KEY_BITS_UNIT 8 44 #define CHACHA20_KEY_LENGTH 32 45 #define CHACHA20_POLY1305_NAME "MBEDTLS_POLY1305_C" 46 47 typedef void MBEDTLS_CTX; 48 49 typedef struct { 50 uint8_t key[AES_256_KEY_LENGTH]; 51 uint32_t keylen; 52 uint8_t iv[GCM_IV_LENGTH]; 53 uint32_t ivLen; 54 uint8_t aad[GCM_MAX_AAD_LENGTH]; 55 uint32_t aadLen; 56 int cipherType; 57 MBEDTLS_CTX *ctx; 58 } CryptPara; 59 60 NSTACKX_EXPORT uint32_t AesGcmEncrypt(const uint8_t *inBuff, uint32_t inLen, CryptPara *cryptPara, 61 uint8_t *outBuff, uint32_t outLen); 62 NSTACKX_EXPORT uint32_t AesGcmDecrypt(uint8_t *inBuff, uint32_t inLen, CryptPara *cryptPara, 63 uint8_t *outBuff, uint32_t outLen); 64 NSTACKX_EXPORT int32_t GetRandBytes(uint8_t *buf, uint32_t len); 65 NSTACKX_EXPORT uint8_t IsCryptoIncluded(void); 66 NSTACKX_EXPORT uint8_t QueryCipherSupportByName(char *name); 67 NSTACKX_EXPORT MBEDTLS_CTX ClearCryptCtx(MBEDTLS_CTX *ctx); 68 NSTACKX_EXPORT MBEDTLS_CTX *CreateCryptCtx(void); 69 70 #endif 71 72 #ifdef __cplusplus 73 } 74 #endif 75 76 #endif 77