1 /* Copyright (c) 2014-2019 Samsung Electronics Co., Ltd. All rights reserved
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
7 * http://www.apache.org/licenses/LICENSE-2.0
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
16 * @file ckm-raw-buffer.h
17 * @author Krzysztof Jackiewicz (k.jackiewicz@samsung.com)
19 * @brief Custom allocator for std
22 #ifndef _SAFE_BUFFER_H_
23 #define _SAFE_BUFFER_H_
28 #include <ckm/ckm-zero-memory.h>
33 struct std_erase_on_dealloc {
34 // MJK: if re-factoring, remember not to inherit from the std::allocator !
35 // MJK: to be replaced with much shorter version once std::allocator_traits
36 // becomes supported in STL containers (i.e. list, vector and string)
37 typedef size_t size_type;
38 typedef ptrdiff_t difference_type;
40 typedef const T *const_pointer;
42 typedef const T &const_reference;
45 std_erase_on_dealloc() = default;
48 std_erase_on_dealloc(const std_erase_on_dealloc<U> &) {}
50 T *allocate(std::size_t n)
52 return static_cast<T *>(::operator new(n * sizeof(T)));
55 void deallocate(T *ptr, std::size_t n)
57 // clear the memory before deleting
58 ZeroMemory(reinterpret_cast<unsigned char*>(ptr), n * sizeof(T));
59 ::operator delete(ptr);
62 template<typename _Tp1>
64 typedef std_erase_on_dealloc<_Tp1> other;
67 void construct(pointer p, const T &val)
72 void destroy(pointer p)
77 size_type max_size() const
83 template <typename T, typename U>
84 inline bool operator==(const std_erase_on_dealloc<T> &,
85 const std_erase_on_dealloc<U> &)
90 template <typename T, typename U>
91 inline bool operator!=(const std_erase_on_dealloc<T> &a,
92 const std_erase_on_dealloc<U> &b)
101 * template <typename T>
102 * using SafeBuffer = std::vector<T, erase_on_dealloc<T>>;
104 * typedef SafeBuffer<unsigned char> RawBuffer
106 * when gcc 4.7/4.8 is available.
108 template <typename T>
110 typedef std::vector<T, std_erase_on_dealloc<T>> Type;
113 // used to pass password and raw key data
114 typedef SafeBuffer<unsigned char>::Type RawBuffer;
116 template <class T, bool Uppercase = false>
117 T hexDump(const RawBuffer &raw) {
119 dump.reserve(2 * raw.size());
120 constexpr char digit[2][16] = {{
121 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
122 'a', 'b', 'c', 'd', 'e', 'f'
124 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
125 'A', 'B', 'C', 'D', 'E', 'F'
127 for (auto &e : raw) {
128 dump.push_back(digit[Uppercase][e / 16]);
129 dump.push_back(digit[Uppercase][e % 16]);
136 #endif //_SAFE_BUFFER_H_