00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00037 #ifndef _SECUREBUFFER_H_INCLUDED
00038 #define _SECUREBUFFER_H_INCLUDED
00039
00040 #include <stdexcept>
00041
00042 #ifdef UNIX
00043
00044
00045 #ifdef __out
00046 #define __out_our_bug_gcc
00047 #undef __out
00048 #endif
00049
00050
00051 #ifdef __in
00052 #define __in_our_bug_gcc
00053 #undef __in
00054 #endif
00055
00056 #include <stdexcept>
00057
00058 #ifdef __out_our_bug_gcc
00059 #define __out
00060 #undef __out_our_bug_gcc
00061 #endif
00062
00063 #ifdef __in_our_bug_gcc
00064 #define __in
00065 #undef __in_our_bug_gcc
00066 #endif
00067
00068 #endif
00069
00070 #ifdef UNIX
00071 # include <memory.h>
00072 #else
00073 # include <windows.h>
00074 #endif // UNIX
00075
00076 #ifndef SecureZeroMemory
00077 #define SecureZeroMemory(ptr,cnt) do { \
00078 volatile char *vptr = (volatile char *)(ptr); \
00079 size_t tmpcnt = (cnt)*sizeof(*ptr); \
00080 while (tmpcnt) { *vptr = 0; vptr++; tmpcnt--; } } while(0)
00081 #endif // SecureZeroMemory
00082
00092 template <typename T>
00093 class CSecureBufferT
00094 {
00095 public:
00104 CSecureBufferT( size_t byteLen = 0 ) : _ptr(0), _len(byteLen) {
00105 if(0 != _len) {
00106 _ptr = new unsigned char[byteLen];
00107 }
00108 }
00109
00115 size_t len() const {
00116 return _len;
00117 }
00118
00127 const T * ptr() const {
00128 return (const T*)_ptr;
00129 }
00130
00136 bool empty() const {
00137 return (0 == _len);
00138 }
00139
00145 T * ptr_rw() {
00146 if(empty()) {
00147 throw std::runtime_error("_ptr is null, can't be writable");
00148 }
00149 return (T*)_ptr;
00150 }
00151
00155 void clean() {
00156 if(!empty()) {
00157 SecureZeroMemory(ptr_rw(),len());
00158 }
00159 }
00160
00164 void copy( const CSecureBufferT<T>& src) {
00165 if( this == &src ) {
00166 return;
00167 }
00168
00169 CSecureBufferT<T> tmp(src.len());
00170 if(!src.empty() && !tmp.empty() ) {
00171 memcpy(tmp.ptr_rw(), src.ptr(), tmp.len());
00172 }
00173 this->swap(tmp);
00174 tmp.clean();
00175 return;
00176 }
00177
00181 void swap( CSecureBufferT<T>& obj) {
00182 if( this == &obj ) {
00183 return;
00184 }
00185 std::swap(this->_ptr, obj._ptr);
00186 std::swap(this->_len, obj._len);
00187 }
00188
00192 ~CSecureBufferT() {
00193 clean();
00194 if(!empty()) {
00195 delete[] _ptr;
00196 }
00197 }
00198 private:
00199 CSecureBufferT( const CSecureBufferT<T>&);
00200 CSecureBufferT<T>& operator=( const CSecureBufferT<T>&);
00201
00202 unsigned char *_ptr;
00203 size_t _len;
00204 };
00205
00214 typedef CSecureBufferT<char> CSecurePin;
00215
00216 #endif // _SECUREBUFFER_H_INCLUDED
00217