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 typedef enum {
33     CIPHER_AES_GCM = 0,
34     CIPHER_CHACHA,
35 } DFileCipherType;
36 
37 #define AES_128_KEY_LENGTH 16
38 #define AES_192_KEY_LENGTH 24
39 #define AES_256_KEY_LENGTH 32
40 #define GCM_IV_LENGTH 12
41 #define GCM_MAX_AAD_LENGTH 64
42 #define GCM_TAG_LENGTH 16
43 #define GCM_ADDED_LEN (GCM_IV_LENGTH + GCM_TAG_LENGTH)
44 #define CHACHA20_KEY_LENGTH 32
45 #define CHACHA20_POLY1305_NAME "chacha20-poly1305"
46 
47 #ifndef SSL_AND_CRYPTO_INCLUDED
48 typedef void EVP_CIPHER_CTX;
49 #undef GCM_TAG_LENGTH
50 #define GCM_TAG_LENGTH 0
51 #undef GCM_ADDED_LEN
52 #define GCM_ADDED_LEN 0
53 #endif // SSL_AND_CRYPTO_INCLUDED
54 
55 typedef struct {
56     uint8_t key[AES_256_KEY_LENGTH];
57     uint32_t keylen;
58     uint8_t iv[GCM_IV_LENGTH];
59     uint32_t ivLen;
60     uint8_t aad[GCM_MAX_AAD_LENGTH];
61     uint32_t aadLen;
62     EVP_CIPHER_CTX *ctx;
63     int cipherType;
64 } CryptPara;
65 
66 typedef struct {
67     const uint8_t *buf;
68     uint32_t len;
69 } AesVec;
70 
71 NSTACKX_EXPORT EVP_CIPHER_CTX *CreateCryptCtx(void);
72 NSTACKX_EXPORT void ClearCryptCtx(EVP_CIPHER_CTX *ctx);
73 NSTACKX_EXPORT uint32_t AesGcmEncryptVec(AesVec *vec, uint32_t vecNum, CryptPara *cryptPara,
74     uint8_t *outBuf, uint32_t outLen);
75 NSTACKX_EXPORT uint32_t AesGcmEncrypt(const uint8_t *inBuff, uint32_t inLen, CryptPara *cryptPara,
76     uint8_t *outBuff, uint32_t outLen);
77 NSTACKX_EXPORT uint32_t AesGcmDecrypt(uint8_t *inBuff, uint32_t inLen, CryptPara *cryptPara,
78     uint8_t *outBuff, uint32_t outLen);
79 NSTACKX_EXPORT int32_t GetRandBytes(uint8_t *buf, uint32_t len);
80 NSTACKX_EXPORT uint8_t IsCryptoIncluded(void);
81 NSTACKX_EXPORT uint8_t QueryCipherSupportByName(char *name);
82 
83 #ifdef __cplusplus
84 }
85 #endif
86 
87 #endif // NSTACKX_OPENSSL_H
88