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