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 #ifndef DESENSITIZE_STRING_STREAM_H 17 #define DESENSITIZE_STRING_STREAM_H 18 19 #include <sstream> 20 21 namespace OHOS { 22 namespace Telephony { 23 namespace DSS { 24 // encrypt Dese()25 inline void Dese() {} 26 } 27 28 /** 29 * @brief Desensitized string stream: used to desensitize fields and output them into strings. 30 * When a field needs to be desensitized, please output DSS::Dese before the field output, 31 * for example: dss << DSS::Dese << field1 << field2. 32 */ 33 class DesensitizeStringStream { 34 using dese = void(*)(); 35 36 public: 37 DesensitizeStringStream() = delete; 38 DesensitizeStringStream(std::string &out, std::stringstream &ss, char separator = ',') separator_(separator)39 : separator_(separator), ss_(ss), out_(out) 40 {} 41 42 inline DesensitizeStringStream &operator<<(dese d) 43 { 44 desensitize_ = true; 45 return *this; 46 } 47 48 template<typename T> 49 inline DesensitizeStringStream &operator<<(T t) 50 { 51 if (desensitize_) { 52 operator()(t); 53 desensitize_ = false; 54 } else { 55 ss_ << t << separator_; 56 } 57 return *this; 58 } 59 60 inline const char* operator*() const 61 { 62 out_ = ss_.str(); 63 return out_.c_str(); 64 } 65 66 private: 67 /* Use bracket operators: desensitize specific fields. */ 68 template<typename T> operator()69 inline void operator()(T &&t) 70 { 71 std::streampos s = ss_.tellp(); 72 ss_ << t; 73 std::streampos e = ss_.tellp(); 74 std::streampos dur = (e - s) / 2; 75 ss_.seekp(-dur, std::ios::end); 76 ss_ << std::string(dur, '*') << separator_ << "\0"; 77 } 78 79 char separator_; 80 bool desensitize_ = false; 81 std::stringstream &ss_; 82 std::string &out_; 83 }; 84 } // namespace Telephony 85 } // namespace OHOS 86 #endif // DESENSITIZE_STRING_STREAM_H