• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2022 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 COMMUNICATION_NETSTACK_TLS_KEY_H
17 #define COMMUNICATION_NETSTACK_TLS_KEY_H
18 
19 #include <memory>
20 #include <string>
21 
22 #include <openssl/bio.h>
23 #include <openssl/dh.h>
24 #include <openssl/dsa.h>
25 #include <openssl/ec.h>
26 #include <openssl/ossl_typ.h>
27 #include <openssl/pem.h>
28 #include <openssl/rsa.h>
29 
30 #include "secure_data.h"
31 #include "tls.h"
32 
33 namespace OHOS {
34 namespace NetStack {
35 class TLSKey {
36 public:
37     TLSKey() = default;
38     ~TLSKey() = default;
39 
40     TLSKey(const SecureData &data, KeyAlgorithm algorithm, const SecureData &passPhrase);
41     TLSKey(const std::string &fileName, KeyAlgorithm algorithm, const SecureData &passPhrase,
42            EncodingFormat format = PEM, KeyType type = PRIVATE_KEY);
43 
44     TLSKey(const TLSKey &other);
45     TLSKey &operator=(const TLSKey &other);
46 
47     [[nodiscard]] KeyAlgorithm Algorithm() const;
48     [[nodiscard]] Handle handle() const;
49     const SecureData &GetKeyPass() const;
50     const SecureData &GetKeyData() const;
51 
52 private:
53     void DecodeData(const SecureData &data, KeyAlgorithm algorithm, const SecureData &passPhrase);
54     void DecodeDer(KeyType type, KeyAlgorithm algorithm, const std::string &fileName, const SecureData &passPhrase);
55     void DecodePem(KeyType type, KeyAlgorithm algorithm, const std::string &fileName, const SecureData &passPhrase);
56     void Clear(bool deep);
57     void SwitchAlgorithm(KeyType type, KeyAlgorithm algorithm, BIO *bio);
58 
59 private:
60     EVP_PKEY *opaque_ = nullptr;
61     RSA *rsa_ = nullptr;
62     DSA *dsa_ = nullptr;
63     DH *dh_ = nullptr;
64     EC_KEY *ec_ = nullptr;
65     EVP_PKEY *genericKey_ = nullptr;
66     SecureData keyPass_;
67     SecureData keyData_;
68     bool keyIsNull_ = true;
69     KeyType keyType_ = PUBLIC_KEY;
70     KeyAlgorithm keyAlgorithm_ = OPAQUE;
71 };
72 } // namespace NetStack
73 } // namespace OHOS
74 #endif // COMMUNICATION_NETSTACK_TLS_KEY_H
75