1 /*
2  * Copyright (c) 2021 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 "types_export.h"
17 
18 #include <cstring>
19 
20 namespace DistributedDB {
21 const size_t CipherPassword::MAX_PASSWORD_SIZE;
22 
CipherPassword()23 CipherPassword::CipherPassword()
24 {}
25 
~CipherPassword()26 CipherPassword::~CipherPassword()
27 {
28     (void)Clear();
29 }
30 
operator ==(const CipherPassword & input) const31 bool CipherPassword::operator==(const CipherPassword &input) const
32 {
33     if (size_ != input.GetSize()) {
34         return false;
35     }
36     return memcmp(data_, input.GetData(), size_) == 0;
37 }
38 
operator !=(const CipherPassword & input) const39 bool CipherPassword::operator!=(const CipherPassword &input) const
40 {
41     return !(*this == input);
42 }
43 
GetSize() const44 size_t CipherPassword::GetSize() const
45 {
46     return size_;
47 }
48 
GetData() const49 const uint8_t* CipherPassword::GetData() const
50 {
51     return data_;
52 }
53 
SetValue(const uint8_t * inputData,size_t inputSize)54 int CipherPassword::SetValue(const uint8_t *inputData, size_t inputSize)
55 {
56     if (inputSize > MAX_PASSWORD_SIZE) {
57         return ErrorCode::OVERSIZE;
58     }
59     if (inputSize != 0 && inputData == nullptr) {
60         return ErrorCode::INVALID_INPUT;
61     }
62 
63     if (inputSize != 0) {
64         std::copy(inputData, inputData + inputSize, data_);
65     }
66 
67     size_t filledSize = std::min(size_, MAX_PASSWORD_SIZE);
68     if (inputSize < filledSize) {
69         std::fill(data_ + inputSize, data_ + filledSize, UCHAR_MAX);
70     }
71 
72     size_ = inputSize;
73     return ErrorCode::OK;
74 }
75 
Clear()76 int CipherPassword::Clear()
77 {
78     return SetValue(nullptr, 0);
79 }
80 } // namespace DistributedDB