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