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 #ifdef UNIX
00041
00042
00043 #ifdef __out
00044 #define __out_our_bug_gcc
00045 #undef __out
00046 #endif
00047
00048
00049 #ifdef __in
00050 #define __in_our_bug_gcc
00051 #undef __in
00052 #endif
00053
00054 #include <stdexcept>
00055
00056 #ifdef __out_our_bug_gcc
00057 #define __out
00058 #undef __out_our_bug_gcc
00059 #endif
00060
00061 #ifdef __in_our_bug_gcc
00062 #define __in
00063 #undef __in_our_bug_gcc
00064 #endif
00065
00066 #endif
00067
00068 #ifdef UNIX
00069 # include <memory.h>
00070 #else
00071 # include <windows.h>
00072 #endif // UNIX
00073
00074 #ifndef SecureZeroMemory
00075 #define SecureZeroMemory(ptr,cnt) do { \
00076 volatile char *vptr = (volatile char *)(ptr); \
00077 size_t tmpcnt = (cnt)*sizeof(*ptr); \
00078 while (tmpcnt) { *vptr = 0; vptr++; tmpcnt--; } } while(0)
00079 #endif // SecureZeroMemory
00080
00090 template <typename T>
00091 class CSecureBufferT
00092 {
00093 public:
00102 CSecureBufferT( size_t byteLen = 0 ) : _ptr(0), _len(byteLen) {
00103 if(0 != _len) {
00104 _ptr = new unsigned char[byteLen];
00105 }
00106 }
00107
00113 size_t len() const {
00114 return _len;
00115 }
00116
00125 const T * ptr() const {
00126 return (const T*)_ptr;
00127 }
00128
00134 bool empty() const {
00135 return (0 == _len);
00136 }
00137
00143 T * ptr_rw() {
00144 if(empty()) {
00145 throw std::runtime_error("_ptr is null, can't be writable");
00146 }
00147 return (T*)_ptr;
00148 }
00149
00153 void clean() {
00154 if(!empty()) {
00155 SecureZeroMemory(ptr_rw(),len());
00156 }
00157 }
00158
00162 void copy( const CSecureBufferT<T>& src) {
00163 if( this == &src ) {
00164 return;
00165 }
00166
00167 CSecureBufferT<T> tmp(src.len());
00168 if(!src.empty() && !tmp.empty() ) {
00169 memcpy(tmp.ptr_rw(), src.ptr(), tmp.len());
00170 }
00171 this->swap(tmp);
00172 tmp.clean();
00173 return;
00174 }
00175
00179 void swap( CSecureBufferT<T>& obj) {
00180 if( this == &obj ) {
00181 return;
00182 }
00183 std::swap(this->_ptr, obj._ptr);
00184 std::swap(this->_len, obj._len);
00185 }
00186
00190 ~CSecureBufferT() {
00191 clean();
00192 if(!empty()) {
00193 delete[] _ptr;
00194 }
00195 }
00196 private:
00197 CSecureBufferT( const CSecureBufferT<T>&);
00198 CSecureBufferT<T>& operator=( const CSecureBufferT<T>&);
00199
00200 unsigned char *_ptr;
00201 size_t _len;
00202 };
00203
00212 typedef CSecureBufferT<char> CSecurePin;
00213
00214 #endif // _SECUREBUFFER_H_INCLUDED
00215