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 {
SecureData()24 SecureData::SecureData() : data_(std::make_unique<char[]>(0)) {}
25
~SecureData()26 SecureData::~SecureData()
27 {
28 if (memset_s(data_.get(), length_, 0, length_) != EOK) {
29 NETSTACK_LOGE("memcpy_s failed!");
30 }
31 }
32
SecureData(const std::string & secureData)33 SecureData::SecureData(const std::string &secureData)
34 : length_(secureData.length()), data_(std::make_unique<char[]>(length_ + 1))
35 {
36 if (memcpy_s(data_.get(), length_, secureData.c_str(), length_) != EOK) {
37 NETSTACK_LOGE("memcpy_s failed!");
38 return;
39 }
40 data_[length_] = '\0';
41 }
42
SecureData(const uint8_t * secureData,size_t length)43 SecureData::SecureData(const uint8_t *secureData, size_t length)
44 {
45 data_ = std::make_unique<char[]>(length);
46 length_ = length;
47 if (memcpy_s(data_.get(), length_, secureData, length_) != EOK) {
48 NETSTACK_LOGE("memcpy_s failed!");
49 }
50 }
51
SecureData(const SecureData & secureData)52 SecureData::SecureData(const SecureData &secureData)
53 {
54 *this = secureData;
55 }
56
operator =(const SecureData & secureData)57 SecureData &SecureData::operator=(const SecureData &secureData)
58 {
59 if (this != &secureData) {
60 length_ = secureData.Length();
61 data_ = std::make_unique<char[]>(length_ + 1);
62 if (memcpy_s(data_.get(), length_, secureData.Data(), length_) != EOK) {
63 NETSTACK_LOGE("memcpy_s failed!");
64 } else {
65 data_[length_] = '\0';
66 }
67 }
68 return *this;
69 }
70
Data() const71 const char *SecureData::Data() const
72 {
73 return data_.get();
74 }
75
Length() const76 size_t SecureData::Length() const
77 {
78 return length_;
79 }
80 } // namespace NetStack
81 } // namespace OHOS
82