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 namespace TlsSocket {
36 class TLSKey {
37 public:
38     TLSKey() = default;
39     ~TLSKey() = default;
40 
41     TLSKey(const SecureData &data, const SecureData &passPhrase);
42     TLSKey(const SecureData &data, KeyAlgorithm algorithm, const SecureData &passPhrase);
43     TLSKey(const std::string &fileName, KeyAlgorithm algorithm, const SecureData &passPhrase,
44            EncodingFormat format = PEM, KeyType type = PRIVATE_KEY);
45 
46     TLSKey(const TLSKey &other);
47     TLSKey &operator=(const TLSKey &other);
48 
49     [[nodiscard]] KeyAlgorithm Algorithm() const;
50     [[nodiscard]] Handle handle() const;
51     const SecureData &GetKeyPass() const;
52     const SecureData &GetKeyData() const;
53 
54 private:
55     void DecodeData(const SecureData &data, const SecureData &passPhrase);
56     void DecodeData(const SecureData &data, KeyAlgorithm algorithm, const SecureData &passPhrase);
57     void DecodeDer(KeyType type, KeyAlgorithm algorithm, const std::string &fileName, const SecureData &passPhrase);
58     void DecodePem(KeyType type, KeyAlgorithm algorithm, const std::string &fileName, const SecureData &passPhrase);
59     void Clear(bool deep);
60     void SwitchAlgorithm(KeyType type, KeyAlgorithm algorithm, BIO *bio);
61 
62 private:
63     EVP_PKEY *opaque_ = nullptr;
64     RSA *rsa_ = nullptr;
65     DSA *dsa_ = nullptr;
66     DH *dh_ = nullptr;
67     EC_KEY *ec_ = nullptr;
68     EVP_PKEY *genericKey_ = nullptr;
69     SecureData keyPass_;
70     SecureData keyData_;
71     bool keyIsNull_ = true;
72     KeyType keyType_ = PUBLIC_KEY;
73     KeyAlgorithm keyAlgorithm_ = OPAQUE;
74 };
75 } // namespace TlsSocket
76 } // namespace NetStack
77 } // namespace OHOS
78 #endif // COMMUNICATION_NETSTACK_TLS_KEY_H
79