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);
31 void Put(const void * data, size_t size, bool last)
33 size_t dataSize = m_ptr - m_buffer;
34 if (dataSize + size > sizeof(m_buffer))
36 memcpy(m_ptr, data, sizeof(m_buffer) - dataSize); // Fill buffer
37 size -= sizeof(m_buffer) - dataSize; // Adjust size
38 data += sizeof(m_buffer) - dataSize; // Adjust data pointer
39 m_proc(m_buffer, m_buffer, sizeof(m_buffer), &m_ctx); // Process
40 m_callback(m_buffer, sizeof(m_buffer), m_data); // Consume
43 memcpy(m_ptr, data, size);
49 char m_buffer[BUFFER_SIZE];
56 void m_tryConsume(bool last)
58 size_t dataSize = (m_ptr - m_buffer) & ~7;
59 size_t remainder = m_ptr - m_buffer - dataSize;
60 if (last && remainder > 0)
67 m_proc(m_buffer, m_buffer, dataSize, &m_ctx);
68 m_callback(m_buffer, dataSize, m_data);
70 memmove(m_buffer, m_buffer + dataSize, remainder);
71 m_ptr = m_buffer + remainder;
75 } // namespace anonymous
77 using STG::ENCRYPT_STREAM;
78 using STG::DECRYPT_STREAM;
80 class ENCRYPT_STREAM::IMPL : public COMMON
83 IMPL(const std::string & key, CALLBACK callback, void * data)
84 : COMMON(key, callback, data, EncryptString)
88 class DECRYPT_STREAM::IMPL : public COMMON
91 IMPL(const std::string & key, CALLBACK callback, void * data)
92 : COMMON(key, callback, data, DecryptString)
96 ENCRYPT_STREAM::ENCRYPT_STREAM(const std::string & key, CALLBACK callback, void * data)
97 : m_impl(new IMPL(key, callback, data))
100 ENCRYPT_STREAM::~ENCRYPT_STREAM()
105 void ENCRYPT_STREAM::Put(const void * data, size_t size, bool last)
107 m_impl->Put(data, size, last);
110 DECRYPT_STREAM::DECRYPT_STREAM(const std::string & key, CALLBACK callback, void * data)
111 : m_impl(new IMPL(key, callback, data))
114 DECRYPT_STREAM::~DECRYPT_STREAM()
119 void DECRYPT_STREAM::Put(const void * data, size_t size, bool last)
121 m_impl->Put(data, size, last);