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_OPENSSL_H 17 #define NSTACKX_OPENSSL_H 18 19 #include "nstackx_common_header.h" 20 21 #ifdef SSL_AND_CRYPTO_INCLUDED 22 #include <openssl/ssl.h> 23 #include <openssl/aes.h> 24 #include <openssl/evp.h> 25 #include <openssl/rand.h> 26 #endif // SSL_AND_CRYPTO_INCLUDED 27 28 #ifdef __cplusplus 29 extern "C" { 30 #endif 31 32 #define AES_128_KEY_LENGTH 16 33 #define AES_192_KEY_LENGTH 24 34 #define AES_256_KEY_LENGTH 32 35 #define GCM_IV_LENGTH 12 36 #define GCM_MAX_AAD_LENGTH 64 37 #define GCM_TAG_LENGTH 16 38 #define GCM_ADDED_LEN (GCM_IV_LENGTH + GCM_TAG_LENGTH) 39 40 #ifndef SSL_AND_CRYPTO_INCLUDED 41 typedef void EVP_CIPHER_CTX; 42 #undef GCM_TAG_LENGTH 43 #define GCM_TAG_LENGTH 0 44 #undef GCM_ADDED_LEN 45 #define GCM_ADDED_LEN 0 46 #endif // SSL_AND_CRYPTO_INCLUDED 47 48 typedef struct { 49 uint8_t key[AES_256_KEY_LENGTH]; 50 uint32_t keylen; 51 uint8_t iv[GCM_IV_LENGTH]; 52 uint32_t ivLen; 53 uint8_t aad[GCM_MAX_AAD_LENGTH]; 54 uint32_t aadLen; 55 EVP_CIPHER_CTX *ctx; 56 } CryptPara; 57 58 typedef struct { 59 const uint8_t *buf; 60 uint32_t len; 61 } AesVec; 62 63 NSTACKX_EXPORT EVP_CIPHER_CTX *CreateCryptCtx(void); 64 NSTACKX_EXPORT void ClearCryptCtx(EVP_CIPHER_CTX *ctx); 65 NSTACKX_EXPORT uint32_t AesGcmEncryptVec(AesVec *vec, uint32_t vecNum, CryptPara *cryptPara, 66 uint8_t *outBuf, uint32_t outLen); 67 NSTACKX_EXPORT uint32_t AesGcmEncrypt(const uint8_t *inBuff, uint32_t inLen, CryptPara *cryptPara, 68 uint8_t *outBuff, uint32_t outLen); 69 NSTACKX_EXPORT uint32_t AesGcmDecrypt(uint8_t *inBuff, uint32_t inLen, CryptPara *cryptPara, 70 uint8_t *outBuff, uint32_t outLen); 71 NSTACKX_EXPORT int32_t GetRandBytes(uint8_t *buf, uint32_t len); 72 NSTACKX_EXPORT uint8_t IsCryptoIncluded(void); 73 74 #ifdef __cplusplus 75 } 76 #endif 77 78 #endif // NSTACKX_OPENSSL_H 79