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