1 #include "stg/bfstream.h"
3 #include "stg/blowfish.h"
10 #ifndef BFSTREAM_BUF_SIZE
11 const size_t BUFFER_SIZE = 1024;
13 const size_t BUFFER_SIZE = BFSTREAM_BUF_SIZE;
19 typedef bool (* CALLBACK)(const void * block, size_t size, void * data);
20 typedef void (* PROC)(void * dest, const void * source, size_t length, const BLOWFISH_CTX * ctx);
22 COMMON(const std::string & key, CALLBACK callback, void * data, PROC proc)
29 InitContext(key.c_str(), key.length(), &m_ctx);
30 memset(m_buffer, 0, sizeof(m_buffer));
33 void Put(const void * data, size_t size, bool last)
35 size_t dataSize = m_ptr - m_buffer;
36 if (dataSize + size > sizeof(m_buffer))
38 memcpy(m_ptr, data, sizeof(m_buffer) - dataSize); // Fill buffer
39 size -= sizeof(m_buffer) - dataSize; // Adjust size
40 data = static_cast<const char *>(data) + sizeof(m_buffer) - dataSize; // Adjust data pointer
41 m_proc(m_buffer, m_buffer, sizeof(m_buffer), &m_ctx); // Process
42 m_ok = m_ok && m_callback(m_buffer, sizeof(m_buffer), m_data); // Consume
47 memcpy(m_ptr, data, size);
52 bool IsOk() const { return m_ok; }
55 char m_buffer[BUFFER_SIZE];
63 void m_tryConsume(bool last)
65 size_t dataSize = (m_ptr - m_buffer) & ~7;
66 size_t remainder = m_ptr - m_buffer - dataSize;
67 if (last && remainder > 0)
74 m_proc(m_buffer, m_buffer, dataSize, &m_ctx);
75 m_ok = m_ok && m_callback(m_buffer, dataSize, m_data);
79 memmove(m_buffer, m_buffer + dataSize, remainder);
80 m_ptr = m_buffer + remainder;
84 } // namespace anonymous
86 using STG::ENCRYPT_STREAM;
87 using STG::DECRYPT_STREAM;
89 class ENCRYPT_STREAM::IMPL : public COMMON
92 IMPL(const std::string & key, CALLBACK callback, void * data)
93 : COMMON(key, callback, data, EncryptString)
97 class DECRYPT_STREAM::IMPL : public COMMON
100 IMPL(const std::string & key, CALLBACK callback, void * data)
101 : COMMON(key, callback, data, DecryptString)
105 ENCRYPT_STREAM::ENCRYPT_STREAM(const std::string & key, CALLBACK callback, void * data)
106 : m_impl(new IMPL(key, callback, data))
109 ENCRYPT_STREAM::~ENCRYPT_STREAM()
114 void ENCRYPT_STREAM::Put(const void * data, size_t size, bool last)
116 m_impl->Put(data, size, last);
119 bool ENCRYPT_STREAM::IsOk() const
121 return m_impl->IsOk();
124 DECRYPT_STREAM::DECRYPT_STREAM(const std::string & key, CALLBACK callback, void * data)
125 : m_impl(new IMPL(key, callback, data))
128 DECRYPT_STREAM::~DECRYPT_STREAM()
133 void DECRYPT_STREAM::Put(const void * data, size_t size, bool last)
135 m_impl->Put(data, size, last);
138 bool DECRYPT_STREAM::IsOk() const
140 return m_impl->IsOk();