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 while (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
48 memcpy(m_ptr, data, size);
53 bool IsOk() const { return m_ok; }
56 char m_buffer[BUFFER_SIZE];
64 void m_tryConsume(bool last)
66 size_t dataSize = (m_ptr - m_buffer) & ~7;
67 size_t remainder = m_ptr - m_buffer - dataSize;
68 if (last && remainder > 0)
73 if (!last && dataSize == 0) // Allow to call callback with 0 data on last call.
75 m_proc(m_buffer, m_buffer, dataSize, &m_ctx);
76 m_ok = m_ok && m_callback(m_buffer, dataSize, m_data);
80 memmove(m_buffer, m_buffer + dataSize, remainder);
81 m_ptr = m_buffer + remainder;
85 } // namespace anonymous
87 using STG::ENCRYPT_STREAM;
88 using STG::DECRYPT_STREAM;
90 class ENCRYPT_STREAM::IMPL : public COMMON
93 IMPL(const std::string & key, CALLBACK callback, void * data)
94 : COMMON(key, callback, data, EncryptString)
98 class DECRYPT_STREAM::IMPL : public COMMON
101 IMPL(const std::string & key, CALLBACK callback, void * data)
102 : COMMON(key, callback, data, DecryptString)
106 ENCRYPT_STREAM::ENCRYPT_STREAM(const std::string & key, CALLBACK callback, void * data)
107 : m_impl(new IMPL(key, callback, data))
110 ENCRYPT_STREAM::~ENCRYPT_STREAM()
115 void ENCRYPT_STREAM::Put(const void * data, size_t size, bool last)
117 m_impl->Put(data, size, last);
120 bool ENCRYPT_STREAM::IsOk() const
122 return m_impl->IsOk();
125 DECRYPT_STREAM::DECRYPT_STREAM(const std::string & key, CALLBACK callback, void * data)
126 : m_impl(new IMPL(key, callback, data))
129 DECRYPT_STREAM::~DECRYPT_STREAM()
134 void DECRYPT_STREAM::Put(const void * data, size_t size, bool last)
136 m_impl->Put(data, size, last);
139 bool DECRYPT_STREAM::IsOk() const
141 return m_impl->IsOk();