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 #include "secure_data.h"
17 
18 #include <securec.h>
19 
20 #include "netstack_log.h"
21 
22 namespace OHOS {
23 namespace NetStack {
24 namespace TlsSocket {
SecureData()25 SecureData::SecureData() : data_(std::make_unique<char[]>(0)) {}
26 
~SecureData()27 SecureData::~SecureData()
28 {
29     if (memset_s(data_.get(), length_, 0, length_) != EOK) {
30         NETSTACK_LOGE("memcpy_s failed!");
31     }
32 }
33 
SecureData(const std::string & secureData)34 SecureData::SecureData(const std::string &secureData)
35     : length_(secureData.length()), data_(std::make_unique<char[]>(length_ + 1))
36 {
37     if (length_ == 0) {
38         return;
39     }
40     data_.get()[length_] = 0;
41     if (memcpy_s(data_.get(), length_, secureData.c_str(), length_) != EOK) {
42         NETSTACK_LOGE("memcpy_s failed!");
43         return;
44     }
45 }
46 
SecureData(const uint8_t * secureData,size_t length)47 SecureData::SecureData(const uint8_t *secureData, size_t length)
48 {
49     data_ = std::make_unique<char[]>(length + 1);
50     length_ = length;
51     data_.get()[length_] = 0;
52     if (memcpy_s(data_.get(), length_, secureData, length_) != EOK) {
53         NETSTACK_LOGE("memcpy_s failed!");
54     }
55 }
56 
SecureData(const SecureData & secureData)57 SecureData::SecureData(const SecureData &secureData)
58 {
59     *this = secureData;
60 }
61 
operator =(const SecureData & secureData)62 SecureData &SecureData::operator=(const SecureData &secureData)
63 {
64     if (this != &secureData) {
65         if (secureData.Length() == 0) {
66             return *this;
67         }
68         length_ = secureData.Length();
69         data_ = std::make_unique<char[]>(length_ + 1);
70         data_.get()[length_] = 0;
71         if (memcpy_s(data_.get(), length_, secureData.Data(), length_) != EOK) {
72             NETSTACK_LOGE("memcpy_s failed!");
73         }
74     }
75     return *this;
76 }
77 
Data() const78 const char *SecureData::Data() const
79 {
80     return data_.get();
81 }
82 
Length() const83 size_t SecureData::Length() const
84 {
85     return length_;
86 }
87 } // namespace TlsSocket
88 } // namespace NetStack
89 } // namespace OHOS
90