• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #define CHACHA20_KEY_LENGTH 32
40 #define CHACHA20_POLY1305_NAME "chacha20-poly1305"
41 
42 #ifndef SSL_AND_CRYPTO_INCLUDED
43 typedef void EVP_CIPHER_CTX;
44 #undef GCM_TAG_LENGTH
45 #define GCM_TAG_LENGTH 0
46 #undef GCM_ADDED_LEN
47 #define GCM_ADDED_LEN 0
48 #endif // SSL_AND_CRYPTO_INCLUDED
49 
50 typedef struct {
51     uint8_t key[AES_256_KEY_LENGTH];
52     uint32_t keylen;
53     uint8_t iv[GCM_IV_LENGTH];
54     uint32_t ivLen;
55     uint8_t aad[GCM_MAX_AAD_LENGTH];
56     uint32_t aadLen;
57     EVP_CIPHER_CTX *ctx;
58     uint8_t cipherType;
59 } CryptPara;
60 
61 typedef struct {
62     const uint8_t *buf;
63     uint32_t len;
64 } AesVec;
65 
66 NSTACKX_EXPORT EVP_CIPHER_CTX *CreateCryptCtx(void);
67 NSTACKX_EXPORT void ClearCryptCtx(EVP_CIPHER_CTX *ctx);
68 NSTACKX_EXPORT uint32_t AesGcmEncryptVec(AesVec *vec, uint32_t vecNum, CryptPara *cryptPara,
69     uint8_t *outBuf, uint32_t outLen);
70 NSTACKX_EXPORT uint32_t AesGcmEncrypt(const uint8_t *inBuff, uint32_t inLen, CryptPara *cryptPara,
71     uint8_t *outBuff, uint32_t outLen);
72 NSTACKX_EXPORT uint32_t AesGcmDecrypt(uint8_t *inBuff, uint32_t inLen, CryptPara *cryptPara,
73     uint8_t *outBuff, uint32_t outLen);
74 NSTACKX_EXPORT int32_t GetRandBytes(uint8_t *buf, uint32_t len);
75 NSTACKX_EXPORT uint8_t IsCryptoIncluded(void);
76 NSTACKX_EXPORT uint8_t QueryCipherSupportByName(char *name);
77 NSTACKX_EXPORT uint8_t IsSupportHardwareAesNi(void);
78 
79 #ifdef __cplusplus
80 }
81 #endif
82 
83 #endif // NSTACKX_OPENSSL_H
84