Main Page | Namespace List | Class Hierarchy | Alphabetical List | Compound List | File List | Namespace Members | Compound Members | File Members

filters.cpp

00001 // filters.cpp - written and placed in the public domain by Wei Dai
00002 
00003 #include "pch.h"
00004 
00005 #ifndef CRYPTOPP_IMPORTS
00006 
00007 #include "filters.h"
00008 #include "mqueue.h"
00009 #include "fltrimpl.h"
00010 #include "argnames.h"
00011 #include <memory>
00012 #include <functional>
00013 
00014 NAMESPACE_BEGIN(CryptoPP)
00015 
00016 Filter::Filter(BufferedTransformation *attachment)
00017         : m_attachment(attachment), m_continueAt(0)
00018 {
00019 }
00020 
00021 BufferedTransformation * Filter::NewDefaultAttachment() const
00022 {
00023         return new MessageQueue;
00024 }
00025 
00026 BufferedTransformation * Filter::AttachedTransformation()
00027 {
00028         if (m_attachment.get() == NULL)
00029                 m_attachment.reset(NewDefaultAttachment());
00030         return m_attachment.get();
00031 }
00032 
00033 const BufferedTransformation *Filter::AttachedTransformation() const
00034 {
00035         if (m_attachment.get() == NULL)
00036                 const_cast<Filter *>(this)->m_attachment.reset(NewDefaultAttachment());
00037         return m_attachment.get();
00038 }
00039 
00040 void Filter::Detach(BufferedTransformation *newOut)
00041 {
00042         m_attachment.reset(newOut);
00043         NotifyAttachmentChange();
00044 }
00045 
00046 void Filter::Insert(Filter *filter)
00047 {
00048         filter->m_attachment.reset(m_attachment.release());
00049         m_attachment.reset(filter);
00050         NotifyAttachmentChange();
00051 }
00052 
00053 unsigned int Filter::CopyRangeTo2(BufferedTransformation &target, unsigned long &begin, unsigned long end, const std::string &channel, bool blocking) const
00054 {
00055         return AttachedTransformation()->CopyRangeTo2(target, begin, end, channel, blocking);
00056 }
00057 
00058 unsigned int Filter::TransferTo2(BufferedTransformation &target, unsigned long &transferBytes, const std::string &channel, bool blocking)
00059 {
00060         return AttachedTransformation()->TransferTo2(target, transferBytes, channel, blocking);
00061 }
00062 
00063 void Filter::Initialize(const NameValuePairs &parameters, int propagation)
00064 {
00065         m_continueAt = 0;
00066         IsolatedInitialize(parameters);
00067         PropagateInitialize(parameters, propagation);
00068 }
00069 
00070 bool Filter::Flush(bool hardFlush, int propagation, bool blocking)
00071 {
00072         switch (m_continueAt)
00073         {
00074         case 0:
00075                 if (IsolatedFlush(hardFlush, blocking))
00076                         return true;
00077         case 1:
00078                 if (OutputFlush(1, hardFlush, propagation, blocking))
00079                         return true;
00080         }
00081         return false;
00082 }
00083 
00084 bool Filter::MessageSeriesEnd(int propagation, bool blocking)
00085 {
00086         switch (m_continueAt)
00087         {
00088         case 0:
00089                 if (IsolatedMessageSeriesEnd(blocking))
00090                         return true;
00091         case 1:
00092                 if (ShouldPropagateMessageSeriesEnd() && OutputMessageSeriesEnd(1, propagation, blocking))
00093                         return true;
00094         }
00095         return false;
00096 }
00097 
00098 void Filter::PropagateInitialize(const NameValuePairs &parameters, int propagation, const std::string &channel)
00099 {
00100         if (propagation)
00101                 AttachedTransformation()->ChannelInitialize(channel, parameters, propagation-1);
00102 }
00103 
00104 unsigned int Filter::Output(int outputSite, const byte *inString, unsigned int length, int messageEnd, bool blocking, const std::string &channel)
00105 {
00106         if (messageEnd)
00107                 messageEnd--;
00108         unsigned int result = AttachedTransformation()->Put2(inString, length, messageEnd, blocking);
00109         m_continueAt = result ? outputSite : 0;
00110         return result;
00111 }
00112 
00113 bool Filter::OutputFlush(int outputSite, bool hardFlush, int propagation, bool blocking, const std::string &channel)
00114 {
00115         if (propagation && AttachedTransformation()->ChannelFlush(channel, hardFlush, propagation-1, blocking))
00116         {
00117                 m_continueAt = outputSite;
00118                 return true;
00119         }
00120         m_continueAt = 0;
00121         return false;
00122 }
00123 
00124 bool Filter::OutputMessageSeriesEnd(int outputSite, int propagation, bool blocking, const std::string &channel)
00125 {
00126         if (propagation && AttachedTransformation()->ChannelMessageSeriesEnd(channel, propagation-1, blocking))
00127         {
00128                 m_continueAt = outputSite;
00129                 return true;
00130         }
00131         m_continueAt = 0;
00132         return false;
00133 }
00134 
00135 // *************************************************************
00136 
00137 unsigned int MeterFilter::Put2(const byte *begin, unsigned int length, int messageEnd, bool blocking)
00138 {
00139         FILTER_BEGIN;
00140         m_currentMessageBytes += length;
00141         m_totalBytes += length;
00142 
00143         if (messageEnd)
00144         {
00145                 m_currentMessageBytes = 0;
00146                 m_currentSeriesMessages++;
00147                 m_totalMessages++;
00148         }
00149         
00150         FILTER_OUTPUT(1, begin, length, messageEnd);
00151         FILTER_END;
00152 }
00153 
00154 bool MeterFilter::IsolatedMessageSeriesEnd(bool blocking)
00155 {
00156         m_currentMessageBytes = 0;
00157         m_currentSeriesMessages = 0;
00158         m_totalMessageSeries++;
00159         return false;
00160 }
00161 
00162 // *************************************************************
00163 
00164 void FilterWithBufferedInput::BlockQueue::ResetQueue(unsigned int blockSize, unsigned int maxBlocks)
00165 {
00166         m_buffer.New(blockSize * maxBlocks);
00167         m_blockSize = blockSize;
00168         m_maxBlocks = maxBlocks;
00169         m_size = 0;
00170         m_begin = m_buffer;
00171 }
00172 
00173 byte *FilterWithBufferedInput::BlockQueue::GetBlock()
00174 {
00175         if (m_size >= m_blockSize)
00176         {
00177                 byte *ptr = m_begin;
00178                 if ((m_begin+=m_blockSize) == m_buffer.end())
00179                         m_begin = m_buffer;
00180                 m_size -= m_blockSize;
00181                 return ptr;
00182         }
00183         else
00184                 return NULL;
00185 }
00186 
00187 byte *FilterWithBufferedInput::BlockQueue::GetContigousBlocks(unsigned int &numberOfBytes)
00188 {
00189         numberOfBytes = STDMIN(numberOfBytes, STDMIN((unsigned int)(m_buffer.end()-m_begin), m_size));
00190         byte *ptr = m_begin;
00191         m_begin += numberOfBytes;
00192         m_size -= numberOfBytes;
00193         if (m_size == 0 || m_begin == m_buffer.end())
00194                 m_begin = m_buffer;
00195         return ptr;
00196 }
00197 
00198 unsigned int FilterWithBufferedInput::BlockQueue::GetAll(byte *outString)
00199 {
00200         unsigned int size = m_size;
00201         unsigned int numberOfBytes = m_maxBlocks*m_blockSize;
00202         const byte *ptr = GetContigousBlocks(numberOfBytes);
00203         memcpy(outString, ptr, numberOfBytes);
00204         memcpy(outString+numberOfBytes, m_begin, m_size);
00205         m_size = 0;
00206         return size;
00207 }
00208 
00209 void FilterWithBufferedInput::BlockQueue::Put(const byte *inString, unsigned int length)
00210 {
00211         assert(m_size + length <= m_buffer.size());
00212         byte *end = (m_size < (unsigned int)(m_buffer.end()-m_begin)) ? m_begin + m_size : m_begin + m_size - m_buffer.size();
00213         unsigned int len = STDMIN(length, (unsigned int)(m_buffer.end()-end));
00214         memcpy(end, inString, len);
00215         if (len < length)
00216                 memcpy(m_buffer, inString+len, length-len);
00217         m_size += length;
00218 }
00219 
00220 FilterWithBufferedInput::FilterWithBufferedInput(BufferedTransformation *attachment)
00221         : Filter(attachment)
00222 {
00223 }
00224 
00225 FilterWithBufferedInput::FilterWithBufferedInput(unsigned int firstSize, unsigned int blockSize, unsigned int lastSize, BufferedTransformation *attachment)
00226         : Filter(attachment), m_firstSize(firstSize), m_blockSize(blockSize), m_lastSize(lastSize)
00227         , m_firstInputDone(false)
00228 {
00229         if (m_firstSize < 0 || m_blockSize < 1 || m_lastSize < 0)
00230                 throw InvalidArgument("FilterWithBufferedInput: invalid buffer size");
00231 
00232         m_queue.ResetQueue(1, m_firstSize);
00233 }
00234 
00235 void FilterWithBufferedInput::IsolatedInitialize(const NameValuePairs &parameters)
00236 {
00237         InitializeDerivedAndReturnNewSizes(parameters, m_firstSize, m_blockSize, m_lastSize);
00238         if (m_firstSize < 0 || m_blockSize < 1 || m_lastSize < 0)
00239                 throw InvalidArgument("FilterWithBufferedInput: invalid buffer size");
00240         m_queue.ResetQueue(1, m_firstSize);
00241         m_firstInputDone = false;
00242 }
00243 
00244 bool FilterWithBufferedInput::IsolatedFlush(bool hardFlush, bool blocking)
00245 {
00246         if (!blocking)
00247                 throw BlockingInputOnly("FilterWithBufferedInput");
00248         
00249         if (hardFlush)
00250                 ForceNextPut();
00251         FlushDerived();
00252         
00253         return false;
00254 }
00255 
00256 unsigned int FilterWithBufferedInput::PutMaybeModifiable(byte *inString, unsigned int length, int messageEnd, bool blocking, bool modifiable)
00257 {
00258         if (!blocking)
00259                 throw BlockingInputOnly("FilterWithBufferedInput");
00260 
00261         if (length != 0)
00262         {
00263                 unsigned int newLength = m_queue.CurrentSize() + length;
00264 
00265                 if (!m_firstInputDone && newLength >= m_firstSize)
00266                 {
00267                         unsigned int len = m_firstSize - m_queue.CurrentSize();
00268                         m_queue.Put(inString, len);
00269                         FirstPut(m_queue.GetContigousBlocks(m_firstSize));
00270                         assert(m_queue.CurrentSize() == 0);
00271                         m_queue.ResetQueue(m_blockSize, (2*m_blockSize+m_lastSize-2)/m_blockSize);
00272 
00273                         inString += len;
00274                         newLength -= m_firstSize;
00275                         m_firstInputDone = true;
00276                 }
00277 
00278                 if (m_firstInputDone)
00279                 {
00280                         if (m_blockSize == 1)
00281                         {
00282                                 while (newLength > m_lastSize && m_queue.CurrentSize() > 0)
00283                                 {
00284                                         unsigned int len = newLength - m_lastSize;
00285                                         byte *ptr = m_queue.GetContigousBlocks(len);
00286                                         NextPutModifiable(ptr, len);
00287                                         newLength -= len;
00288                                 }
00289 
00290                                 if (newLength > m_lastSize)
00291                                 {
00292                                         unsigned int len = newLength - m_lastSize;
00293                                         NextPutMaybeModifiable(inString, len, modifiable);
00294                                         inString += len;
00295                                         newLength -= len;
00296                                 }
00297                         }
00298                         else
00299                         {
00300                                 while (newLength >= m_blockSize + m_lastSize && m_queue.CurrentSize() >= m_blockSize)
00301                                 {
00302                                         NextPutModifiable(m_queue.GetBlock(), m_blockSize);
00303                                         newLength -= m_blockSize;
00304                                 }
00305 
00306                                 if (newLength >= m_blockSize + m_lastSize && m_queue.CurrentSize() > 0)
00307                                 {
00308                                         assert(m_queue.CurrentSize() < m_blockSize);
00309                                         unsigned int len = m_blockSize - m_queue.CurrentSize();
00310                                         m_queue.Put(inString, len);
00311                                         inString += len;
00312                                         NextPutModifiable(m_queue.GetBlock(), m_blockSize);
00313                                         newLength -= m_blockSize;
00314                                 }
00315 
00316                                 if (newLength >= m_blockSize + m_lastSize)
00317                                 {
00318                                         unsigned int len = RoundDownToMultipleOf(newLength - m_lastSize, m_blockSize);
00319                                         NextPutMaybeModifiable(inString, len, modifiable);
00320                                         inString += len;
00321                                         newLength -= len;
00322                                 }
00323                         }
00324                 }
00325 
00326                 m_queue.Put(inString, newLength - m_queue.CurrentSize());
00327         }
00328 
00329         if (messageEnd)
00330         {
00331                 if (!m_firstInputDone && m_firstSize==0)
00332                         FirstPut(NULL);
00333 
00334                 SecByteBlock temp(m_queue.CurrentSize());
00335                 m_queue.GetAll(temp);
00336                 LastPut(temp, temp.size());
00337 
00338                 m_firstInputDone = false;
00339                 m_queue.ResetQueue(1, m_firstSize);
00340 
00341                 Output(1, NULL, 0, messageEnd, blocking);
00342         }
00343         return 0;
00344 }
00345 
00346 void FilterWithBufferedInput::ForceNextPut()
00347 {
00348         if (!m_firstInputDone)
00349                 return;
00350         
00351         if (m_blockSize > 1)
00352         {
00353                 while (m_queue.CurrentSize() >= m_blockSize)
00354                         NextPutModifiable(m_queue.GetBlock(), m_blockSize);
00355         }
00356         else
00357         {
00358                 unsigned int len;
00359                 while ((len = m_queue.CurrentSize()) > 0)
00360                         NextPutModifiable(m_queue.GetContigousBlocks(len), len);
00361         }
00362 }
00363 
00364 void FilterWithBufferedInput::NextPutMultiple(const byte *inString, unsigned int length)
00365 {
00366         assert(m_blockSize > 1);        // m_blockSize = 1 should always override this function
00367         while (length > 0)
00368         {
00369                 assert(length >= m_blockSize);
00370                 NextPutSingle(inString);
00371                 inString += m_blockSize;
00372                 length -= m_blockSize;
00373         }
00374 }
00375 
00376 // *************************************************************
00377 
00378 void Redirector::ChannelInitialize(const std::string &channel, const NameValuePairs &parameters, int propagation)
00379 {
00380         if (channel.empty())
00381         {
00382                 m_target = parameters.GetValueWithDefault("RedirectionTargetPointer", (BufferedTransformation*)NULL);
00383                 m_passSignal = parameters.GetValueWithDefault("PassSignal", true);
00384         }
00385 
00386         if (m_target && m_passSignal)
00387                 m_target->ChannelInitialize(channel, parameters, propagation);
00388 }
00389 
00390 // *************************************************************
00391 
00392 ProxyFilter::ProxyFilter(BufferedTransformation *filter, unsigned int firstSize, unsigned int lastSize, BufferedTransformation *attachment)
00393         : FilterWithBufferedInput(firstSize, 1, lastSize, attachment), m_filter(filter), m_proxy(NULL)
00394 {
00395         if (m_filter.get())
00396                 m_filter->Attach(m_proxy = new OutputProxy(*this, false));
00397 }
00398 
00399 void ProxyFilter::IsolatedFlush(bool completeFlush)
00400 {
00401         if (m_filter.get())
00402         {
00403                 bool passSignal = m_proxy->GetPassSignal();
00404                 m_proxy->SetPassSignal(false);
00405                 m_filter->Flush(completeFlush, -1);
00406                 m_proxy->SetPassSignal(passSignal);
00407         }
00408 }
00409 
00410 void ProxyFilter::SetFilter(Filter *filter)
00411 {
00412         bool passSignal = m_proxy ? m_proxy->GetPassSignal() : false;
00413         m_filter.reset(filter);
00414         if (filter)
00415         {
00416                 std::auto_ptr<OutputProxy> temp(m_proxy = new OutputProxy(*this, passSignal));
00417                 m_filter->TransferAllTo(*m_proxy);
00418                 m_filter->Attach(temp.release());
00419         }
00420         else
00421                 m_proxy=NULL;
00422 }
00423 
00424 void ProxyFilter::NextPutMultiple(const byte *s, unsigned int len) 
00425 {
00426         if (m_filter.get())
00427                 m_filter->Put(s, len);
00428 }
00429 
00430 // *************************************************************
00431 
00432 unsigned int ArraySink::Put2(const byte *begin, unsigned int length, int messageEnd, bool blocking)
00433 {
00434         memcpy(m_buf+m_total, begin, STDMIN(length, SaturatingSubtract(m_size, m_total)));
00435         m_total += length;
00436         return 0;
00437 }
00438 
00439 byte * ArraySink::CreatePutSpace(unsigned int &size)
00440 {
00441         size = m_size - m_total;
00442         return m_buf + m_total;
00443 }
00444 
00445 void ArraySink::IsolatedInitialize(const NameValuePairs &parameters)
00446 {
00447         ByteArrayParameter array;
00448         if (!parameters.GetValue(Name::OutputBuffer(), array))
00449                 throw InvalidArgument("ArraySink: missing OutputBuffer argument");
00450         m_buf = array.begin();
00451         m_size = array.size();
00452         m_total = 0;
00453 }
00454 
00455 unsigned int ArrayXorSink::Put2(const byte *begin, unsigned int length, int messageEnd, bool blocking)
00456 {
00457         xorbuf(m_buf+m_total, begin, STDMIN(length, SaturatingSubtract(m_size, m_total)));
00458         m_total += length;
00459         return 0;
00460 }
00461 
00462 // *************************************************************
00463 
00464 unsigned int StreamTransformationFilter::LastBlockSize(StreamTransformation &c, BlockPaddingScheme padding)
00465 {
00466         if (c.MinLastBlockSize() > 0)
00467                 return c.MinLastBlockSize();
00468         else if (c.MandatoryBlockSize() > 1 && !c.IsForwardTransformation() && padding != NO_PADDING && padding != ZEROS_PADDING)
00469                 return c.MandatoryBlockSize();
00470         else
00471                 return 0;
00472 }
00473 
00474 StreamTransformationFilter::StreamTransformationFilter(StreamTransformation &c, BufferedTransformation *attachment, BlockPaddingScheme padding)
00475    : FilterWithBufferedInput(0, c.MandatoryBlockSize(), LastBlockSize(c, padding), attachment)
00476         , m_cipher(c)
00477 {
00478         assert(c.MinLastBlockSize() == 0 || c.MinLastBlockSize() > c.MandatoryBlockSize());
00479 
00480         bool isBlockCipher = (c.MandatoryBlockSize() > 1 && c.MinLastBlockSize() == 0);
00481 
00482         if (padding == DEFAULT_PADDING)
00483         {
00484                 if (isBlockCipher)
00485                         m_padding = PKCS_PADDING;
00486                 else
00487                         m_padding = NO_PADDING;
00488         }
00489         else
00490                 m_padding = padding;
00491 
00492         if (!isBlockCipher && (m_padding == PKCS_PADDING || m_padding == ONE_AND_ZEROS_PADDING))
00493                 throw InvalidArgument("StreamTransformationFilter: PKCS_PADDING and ONE_AND_ZEROS_PADDING cannot be used with " + c.AlgorithmName());
00494 }
00495 
00496 void StreamTransformationFilter::FirstPut(const byte *inString)
00497 {
00498         m_optimalBufferSize = m_cipher.OptimalBlockSize();
00499         m_optimalBufferSize = STDMAX(m_optimalBufferSize, RoundDownToMultipleOf(4096U, m_optimalBufferSize));
00500 }
00501 
00502 void StreamTransformationFilter::NextPutMultiple(const byte *inString, unsigned int length)
00503 {
00504         if (!length)
00505                 return;
00506 
00507         unsigned int s = m_cipher.MandatoryBlockSize();
00508 
00509         do
00510         {
00511                 unsigned int len = m_optimalBufferSize;
00512                 byte *space = HelpCreatePutSpace(*AttachedTransformation(), NULL_CHANNEL, s, length, len);
00513                 if (len < length)
00514                 {
00515                         if (len == m_optimalBufferSize)
00516                                 len -= m_cipher.GetOptimalBlockSizeUsed();
00517                         len = RoundDownToMultipleOf(len, s);
00518                 }
00519                 else
00520                         len = length;
00521                 m_cipher.ProcessString(space, inString, len);
00522                 AttachedTransformation()->PutModifiable(space, len);
00523                 inString += len;
00524                 length -= len;
00525         }
00526         while (length > 0);
00527 }
00528 
00529 void StreamTransformationFilter::NextPutModifiable(byte *inString, unsigned int length)
00530 {
00531         m_cipher.ProcessString(inString, length);
00532         AttachedTransformation()->PutModifiable(inString, length);
00533 }
00534 
00535 void StreamTransformationFilter::LastPut(const byte *inString, unsigned int length)
00536 {
00537         byte *space = NULL;
00538         
00539         switch (m_padding)
00540         {
00541         case NO_PADDING:
00542         case ZEROS_PADDING:
00543                 if (length > 0)
00544                 {
00545                         unsigned int minLastBlockSize = m_cipher.MinLastBlockSize();
00546                         bool isForwardTransformation = m_cipher.IsForwardTransformation();
00547 
00548                         if (isForwardTransformation && m_padding == ZEROS_PADDING && (minLastBlockSize == 0 || length < minLastBlockSize))
00549                         {
00550                                 // do padding
00551                                 unsigned int blockSize = STDMAX(minLastBlockSize, m_cipher.MandatoryBlockSize());
00552                                 space = HelpCreatePutSpace(*AttachedTransformation(), NULL_CHANNEL, blockSize);
00553                                 memcpy(space, inString, length);
00554                                 memset(space + length, 0, blockSize - length);
00555                                 m_cipher.ProcessLastBlock(space, space, blockSize);
00556                                 AttachedTransformation()->Put(space, blockSize);
00557                         }
00558                         else
00559                         {
00560                                 if (minLastBlockSize == 0)
00561                                 {
00562                                         if (isForwardTransformation)
00563                                                 throw InvalidDataFormat("StreamTransformationFilter: plaintext length is not a multiple of block size and NO_PADDING is specified");
00564                                         else
00565                                                 throw InvalidCiphertext("StreamTransformationFilter: ciphertext length is not a multiple of block size");
00566                                 }
00567 
00568                                 space = HelpCreatePutSpace(*AttachedTransformation(), NULL_CHANNEL, length, m_optimalBufferSize);
00569                                 m_cipher.ProcessLastBlock(space, inString, length);
00570                                 AttachedTransformation()->Put(space, length);
00571                         }
00572                 }
00573                 break;
00574 
00575         case PKCS_PADDING:
00576         case ONE_AND_ZEROS_PADDING:
00577                 unsigned int s;
00578                 s = m_cipher.MandatoryBlockSize();
00579                 assert(s > 1);
00580                 space = HelpCreatePutSpace(*AttachedTransformation(), NULL_CHANNEL, s, m_optimalBufferSize);
00581                 if (m_cipher.IsForwardTransformation())
00582                 {
00583                         assert(length < s);
00584                         memcpy(space, inString, length);
00585                         if (m_padding == PKCS_PADDING)
00586                         {
00587                                 assert(s < 256);
00588                                 byte pad = s-length;
00589                                 memset(space+length, pad, s-length);
00590                         }
00591                         else
00592                         {
00593                                 space[length] = 1;
00594                                 memset(space+length+1, 0, s-length-1);
00595                         }
00596                         m_cipher.ProcessData(space, space, s);
00597                         AttachedTransformation()->Put(space, s);
00598                 }
00599                 else
00600                 {
00601                         if (length != s)
00602                                 throw InvalidCiphertext("StreamTransformationFilter: ciphertext length is not a multiple of block size");
00603                         m_cipher.ProcessData(space, inString, s);
00604                         if (m_padding == PKCS_PADDING)
00605                         {
00606                                 byte pad = space[s-1];
00607                                 if (pad < 1 || pad > s || std::find_if(space+s-pad, space+s, std::bind2nd(std::not_equal_to<byte>(), pad)) != space+s)
00608                                         throw InvalidCiphertext("StreamTransformationFilter: invalid PKCS #7 block padding found");
00609                                 length = s-pad;
00610                         }
00611                         else
00612                         {
00613                                 while (length > 1 && space[length-1] == '\0')
00614                                         --length;
00615                                 if (space[--length] != '\1')
00616                                         throw InvalidCiphertext("StreamTransformationFilter: invalid ones-and-zeros padding found");
00617                         }
00618                         AttachedTransformation()->Put(space, length);
00619                 }
00620                 break;
00621 
00622         default:
00623                 assert(false);
00624         }
00625 }
00626 
00627 // *************************************************************
00628 
00629 void HashFilter::IsolatedInitialize(const NameValuePairs &parameters)
00630 {
00631         m_putMessage = parameters.GetValueWithDefault(Name::PutMessage(), false);
00632         m_hashModule.Restart();
00633 }
00634 
00635 unsigned int HashFilter::Put2(const byte *inString, unsigned int length, int messageEnd, bool blocking)
00636 {
00637         FILTER_BEGIN;
00638         m_hashModule.Update(inString, length);
00639         if (m_putMessage)
00640                 FILTER_OUTPUT(1, inString, length, 0);
00641         if (messageEnd)
00642         {
00643                 {
00644                         unsigned int size, digestSize = m_hashModule.DigestSize();
00645                         m_space = HelpCreatePutSpace(*AttachedTransformation(), NULL_CHANNEL, digestSize, digestSize, size = digestSize);
00646                         m_hashModule.Final(m_space);
00647                 }
00648                 FILTER_OUTPUT(2, m_space, m_hashModule.DigestSize(), messageEnd);
00649         }
00650         FILTER_END_NO_MESSAGE_END;
00651 }
00652 
00653 // *************************************************************
00654 
00655 HashVerificationFilter::HashVerificationFilter(HashTransformation &hm, BufferedTransformation *attachment, word32 flags)
00656         : FilterWithBufferedInput(attachment)
00657         , m_hashModule(hm)
00658 {
00659         IsolatedInitialize(MakeParameters(Name::HashVerificationFilterFlags(), flags));
00660 }
00661 
00662 void HashVerificationFilter::InitializeDerivedAndReturnNewSizes(const NameValuePairs &parameters, unsigned int &firstSize, unsigned int &blockSize, unsigned int &lastSize)
00663 {
00664         m_flags = parameters.GetValueWithDefault(Name::HashVerificationFilterFlags(), (word32)DEFAULT_FLAGS);
00665         m_hashModule.Restart();
00666         unsigned int size = m_hashModule.DigestSize();
00667         m_verified = false;
00668         firstSize = m_flags & HASH_AT_BEGIN ? size : 0;
00669         blockSize = 1;
00670         lastSize = m_flags & HASH_AT_BEGIN ? 0 : size;
00671 }
00672 
00673 void HashVerificationFilter::FirstPut(const byte *inString)
00674 {
00675         if (m_flags & HASH_AT_BEGIN)
00676         {
00677                 m_expectedHash.New(m_hashModule.DigestSize());
00678                 memcpy(m_expectedHash, inString, m_expectedHash.size());
00679                 if (m_flags & PUT_HASH)
00680                         AttachedTransformation()->Put(inString, m_expectedHash.size());
00681         }
00682 }
00683 
00684 void HashVerificationFilter::NextPutMultiple(const byte *inString, unsigned int length)
00685 {
00686         m_hashModule.Update(inString, length);
00687         if (m_flags & PUT_MESSAGE)
00688                 AttachedTransformation()->Put(inString, length);
00689 }
00690 
00691 void HashVerificationFilter::LastPut(const byte *inString, unsigned int length)
00692 {
00693         if (m_flags & HASH_AT_BEGIN)
00694         {
00695                 assert(length == 0);
00696                 m_verified = m_hashModule.Verify(m_expectedHash);
00697         }
00698         else
00699         {
00700                 m_verified = (length==m_hashModule.DigestSize() && m_hashModule.Verify(inString));
00701                 if (m_flags & PUT_HASH)
00702                         AttachedTransformation()->Put(inString, length);
00703         }
00704 
00705         if (m_flags & PUT_RESULT)
00706                 AttachedTransformation()->Put(m_verified);
00707 
00708         if ((m_flags & THROW_EXCEPTION) && !m_verified)
00709                 throw HashVerificationFailed();
00710 }
00711 
00712 // *************************************************************
00713 
00714 void SignerFilter::IsolatedInitialize(const NameValuePairs &parameters)
00715 {
00716         m_putMessage = parameters.GetValueWithDefault(Name::PutMessage(), false);
00717         m_messageAccumulator.reset(m_signer.NewSignatureAccumulator());
00718 }
00719 
00720 unsigned int SignerFilter::Put2(const byte *inString, unsigned int length, int messageEnd, bool blocking)
00721 {
00722         FILTER_BEGIN;
00723         m_messageAccumulator->Update(inString, length);
00724         if (m_putMessage)
00725                 FILTER_OUTPUT(1, inString, length, 0);
00726         if (messageEnd)
00727         {
00728                 m_buf.New(m_signer.SignatureLength());
00729                 m_signer.Sign(m_rng, m_messageAccumulator.release(), m_buf);
00730                 FILTER_OUTPUT(2, m_buf, m_buf.size(), messageEnd);
00731                 m_messageAccumulator.reset(m_signer.NewSignatureAccumulator());
00732         }
00733         FILTER_END_NO_MESSAGE_END;
00734 }
00735 
00736 SignatureVerificationFilter::SignatureVerificationFilter(const PK_Verifier &verifier, BufferedTransformation *attachment, word32 flags)
00737         : FilterWithBufferedInput(attachment)
00738         , m_verifier(verifier)
00739 {
00740         IsolatedInitialize(MakeParameters(Name::SignatureVerificationFilterFlags(), flags));
00741 }
00742 
00743 void SignatureVerificationFilter::InitializeDerivedAndReturnNewSizes(const NameValuePairs &parameters, unsigned int &firstSize, unsigned int &blockSize, unsigned int &lastSize)
00744 {
00745         m_flags = parameters.GetValueWithDefault(Name::SignatureVerificationFilterFlags(), (word32)DEFAULT_FLAGS);
00746         m_messageAccumulator.reset(m_verifier.NewVerificationAccumulator());
00747         unsigned int size = m_verifier.SignatureLength();
00748         m_verified = false;
00749         firstSize = m_flags & SIGNATURE_AT_BEGIN ? size : 0;
00750         blockSize = 1;
00751         lastSize = m_flags & SIGNATURE_AT_BEGIN ? 0 : size;
00752 }
00753 
00754 void SignatureVerificationFilter::FirstPut(const byte *inString)
00755 {
00756         if (m_flags & SIGNATURE_AT_BEGIN)
00757         {
00758                 if (m_verifier.SignatureUpfrontForVerification())
00759                         m_verifier.InitializeVerificationAccumulator(*m_messageAccumulator, inString);
00760                 else
00761                 {
00762                         m_signature.New(m_verifier.SignatureLength());
00763                         memcpy(m_signature, inString, m_signature.size());
00764                 }
00765 
00766                 if (m_flags & PUT_SIGNATURE)
00767                         AttachedTransformation()->Put(inString, m_signature.size());
00768         }
00769         else
00770         {
00771                 assert(!m_verifier.SignatureUpfrontForVerification());
00772         }
00773 }
00774 
00775 void SignatureVerificationFilter::NextPutMultiple(const byte *inString, unsigned int length)
00776 {
00777         m_messageAccumulator->Update(inString, length);
00778         if (m_flags & PUT_MESSAGE)
00779                 AttachedTransformation()->Put(inString, length);
00780 }
00781 
00782 void SignatureVerificationFilter::LastPut(const byte *inString, unsigned int length)
00783 {
00784         if (m_flags & SIGNATURE_AT_BEGIN)
00785         {
00786                 assert(length == 0);
00787                 m_verified = m_verifier.Verify(m_messageAccumulator.release(), m_signature);
00788         }
00789         else
00790         {
00791                 m_verified = (length==m_verifier.SignatureLength() && m_verifier.Verify(m_messageAccumulator.release(), inString));
00792                 if (m_flags & PUT_SIGNATURE)
00793                         AttachedTransformation()->Put(inString, length);
00794         }
00795 
00796         if (m_flags & PUT_RESULT)
00797                 AttachedTransformation()->Put(m_verified);
00798 
00799         if ((m_flags & THROW_EXCEPTION) && !m_verified)
00800                 throw SignatureVerificationFailed();
00801 }
00802 
00803 // *************************************************************
00804 
00805 unsigned int Source::PumpAll2(bool blocking)
00806 {
00807         // TODO: switch length type
00808         unsigned long i = UINT_MAX;
00809         RETURN_IF_NONZERO(Pump2(i, blocking));
00810         unsigned int j = UINT_MAX;
00811         return PumpMessages2(j, blocking);
00812 }
00813 
00814 bool Store::GetNextMessage()
00815 {
00816         if (!m_messageEnd && !AnyRetrievable())
00817         {
00818                 m_messageEnd=true;
00819                 return true;
00820         }
00821         else
00822                 return false;
00823 }
00824 
00825 unsigned int Store::CopyMessagesTo(BufferedTransformation &target, unsigned int count, const std::string &channel) const
00826 {
00827         if (m_messageEnd || count == 0)
00828                 return 0;
00829         else
00830         {
00831                 CopyTo(target, ULONG_MAX, channel);
00832                 if (GetAutoSignalPropagation())
00833                         target.ChannelMessageEnd(channel, GetAutoSignalPropagation()-1);
00834                 return 1;
00835         }
00836 }
00837 
00838 void StringStore::StoreInitialize(const NameValuePairs &parameters)
00839 {
00840         ConstByteArrayParameter array;
00841         if (!parameters.GetValue(Name::InputBuffer(), array))
00842                 throw InvalidArgument("StringStore: missing InputBuffer argument");
00843         m_store = array.begin();
00844         m_length = array.size();
00845         m_count = 0;
00846 }
00847 
00848 unsigned int StringStore::TransferTo2(BufferedTransformation &target, unsigned long &transferBytes, const std::string &channel, bool blocking)
00849 {
00850         unsigned long position = 0;
00851         unsigned int blockedBytes = CopyRangeTo2(target, position, transferBytes, channel, blocking);
00852         m_count += position;
00853         transferBytes = position;
00854         return blockedBytes;
00855 }
00856 
00857 unsigned int StringStore::CopyRangeTo2(BufferedTransformation &target, unsigned long &begin, unsigned long end, const std::string &channel, bool blocking) const
00858 {
00859         unsigned int i = (unsigned int)STDMIN((unsigned long)m_count+begin, (unsigned long)m_length);
00860         unsigned int len = (unsigned int)STDMIN((unsigned long)m_length-i, end-begin);
00861         unsigned int blockedBytes = target.ChannelPut2(channel, m_store+i, len, 0, blocking);
00862         if (!blockedBytes)
00863                 begin += len;
00864         return blockedBytes;
00865 }
00866 
00867 unsigned int RandomNumberStore::TransferTo2(BufferedTransformation &target, unsigned long &transferBytes, const std::string &channel, bool blocking)
00868 {
00869         if (!blocking)
00870                 throw NotImplemented("RandomNumberStore: nonblocking transfer is not implemented by this object");
00871 
00872         unsigned long transferMax = transferBytes;
00873         for (transferBytes = 0; transferBytes<transferMax && m_count < m_length; ++transferBytes, ++m_count)
00874                 target.ChannelPut(channel, m_rng.GenerateByte());
00875         return 0;
00876 }
00877 
00878 unsigned int NullStore::CopyRangeTo2(BufferedTransformation &target, unsigned long &begin, unsigned long end, const std::string &channel, bool blocking) const
00879 {
00880         static const byte nullBytes[128] = {0};
00881         while (begin < end)
00882         {
00883                 unsigned int len = STDMIN(end-begin, 128UL);
00884                 unsigned int blockedBytes = target.ChannelPut2(channel, nullBytes, len, 0, blocking);
00885                 if (blockedBytes)
00886                         return blockedBytes;
00887                 begin += len;
00888         }
00889         return 0;
00890 }
00891 
00892 unsigned int NullStore::TransferTo2(BufferedTransformation &target, unsigned long &transferBytes, const std::string &channel, bool blocking)
00893 {
00894         unsigned long begin = 0;
00895         unsigned int blockedBytes = NullStore::CopyRangeTo2(target, begin, transferBytes, channel, blocking);
00896         transferBytes = begin;
00897         m_size -= begin;
00898         return blockedBytes;
00899 }
00900 
00901 NAMESPACE_END
00902 
00903 #endif

Generated on Tue Jul 8 23:34:14 2003 for Crypto++ by doxygen 1.3.2