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 void (* 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)
28 InitContext(key.c_str(), key.length(), &m_ctx);
29 memset(m_buffer, 0, sizeof(m_buffer));
32 void Put(const void * data, size_t size, bool last)
34 size_t dataSize = m_ptr - m_buffer;
35 if (dataSize + size > sizeof(m_buffer))
37 memcpy(m_ptr, data, sizeof(m_buffer) - dataSize); // Fill buffer
38 size -= sizeof(m_buffer) - dataSize; // Adjust size
39 data = static_cast<const char *>(data) + sizeof(m_buffer) - dataSize; // Adjust data pointer
40 m_proc(m_buffer, m_buffer, sizeof(m_buffer), &m_ctx); // Process
41 m_callback(m_buffer, sizeof(m_buffer), m_data); // Consume
44 memcpy(m_ptr, data, size);
50 char m_buffer[BUFFER_SIZE];
57 void m_tryConsume(bool last)
59 size_t dataSize = (m_ptr - m_buffer) & ~7;
60 size_t remainder = m_ptr - m_buffer - dataSize;
61 if (last && remainder > 0)
68 m_proc(m_buffer, m_buffer, dataSize, &m_ctx);
69 m_callback(m_buffer, dataSize, m_data);
71 memmove(m_buffer, m_buffer + dataSize, remainder);
72 m_ptr = m_buffer + remainder;
76 } // namespace anonymous
78 using STG::ENCRYPT_STREAM;
79 using STG::DECRYPT_STREAM;
81 class ENCRYPT_STREAM::IMPL : public COMMON
84 IMPL(const std::string & key, CALLBACK callback, void * data)
85 : COMMON(key, callback, data, EncryptString)
89 class DECRYPT_STREAM::IMPL : public COMMON
92 IMPL(const std::string & key, CALLBACK callback, void * data)
93 : COMMON(key, callback, data, DecryptString)
97 ENCRYPT_STREAM::ENCRYPT_STREAM(const std::string & key, CALLBACK callback, void * data)
98 : m_impl(new IMPL(key, callback, data))
101 ENCRYPT_STREAM::~ENCRYPT_STREAM()
106 void ENCRYPT_STREAM::Put(const void * data, size_t size, bool last)
108 m_impl->Put(data, size, last);
111 DECRYPT_STREAM::DECRYPT_STREAM(const std::string & key, CALLBACK callback, void * data)
112 : m_impl(new IMPL(key, callback, data))
115 DECRYPT_STREAM::~DECRYPT_STREAM()
120 void DECRYPT_STREAM::Put(const void * data, size_t size, bool last)
122 m_impl->Put(data, size, last);