monotone

monotone Mtn Source Tree

Root/cryptopp/filters.cpp

1// filters.cpp - written and placed in the public domain by Wei Dai
2
3#include "pch.h"
4#include "filters.h"
5#include "mqueue.h"
6#include "fltrimpl.h"
7#include "argnames.h"
8#include <memory>
9#include <functional>
10
11NAMESPACE_BEGIN(CryptoPP)
12
13Filter::Filter(BufferedTransformation *attachment)
14: m_attachment(attachment), m_continueAt(0)
15{
16}
17
18BufferedTransformation * Filter::NewDefaultAttachment() const
19{
20return new MessageQueue;
21}
22
23BufferedTransformation * Filter::AttachedTransformation()
24{
25if (m_attachment.get() == NULL)
26m_attachment.reset(NewDefaultAttachment());
27return m_attachment.get();
28}
29
30const BufferedTransformation *Filter::AttachedTransformation() const
31{
32if (m_attachment.get() == NULL)
33const_cast<Filter *>(this)->m_attachment.reset(NewDefaultAttachment());
34return m_attachment.get();
35}
36
37void Filter::Detach(BufferedTransformation *newOut)
38{
39m_attachment.reset(newOut);
40NotifyAttachmentChange();
41}
42
43void Filter::Insert(Filter *filter)
44{
45filter->m_attachment.reset(m_attachment.release());
46m_attachment.reset(filter);
47NotifyAttachmentChange();
48}
49
50unsigned int Filter::CopyRangeTo2(BufferedTransformation &target, unsigned long &begin, unsigned long end, const std::string &channel, bool blocking) const
51{
52return AttachedTransformation()->CopyRangeTo2(target, begin, end, channel, blocking);
53}
54
55unsigned int Filter::TransferTo2(BufferedTransformation &target, unsigned long &transferBytes, const std::string &channel, bool blocking)
56{
57return AttachedTransformation()->TransferTo2(target, transferBytes, channel, blocking);
58}
59
60void Filter::Initialize(const NameValuePairs &parameters, int propagation)
61{
62m_continueAt = 0;
63IsolatedInitialize(parameters);
64PropagateInitialize(parameters, propagation);
65}
66
67bool Filter::Flush(bool hardFlush, int propagation, bool blocking)
68{
69switch (m_continueAt)
70{
71case 0:
72if (IsolatedFlush(hardFlush, blocking))
73return true;
74case 1:
75if (OutputFlush(1, hardFlush, propagation, blocking))
76return true;
77}
78return false;
79}
80
81bool Filter::MessageSeriesEnd(int propagation, bool blocking)
82{
83switch (m_continueAt)
84{
85case 0:
86if (IsolatedMessageSeriesEnd(blocking))
87return true;
88case 1:
89if (ShouldPropagateMessageSeriesEnd() && OutputMessageSeriesEnd(1, propagation, blocking))
90return true;
91}
92return false;
93}
94
95void Filter::PropagateInitialize(const NameValuePairs &parameters, int propagation, const std::string &channel)
96{
97if (propagation)
98AttachedTransformation()->ChannelInitialize(channel, parameters, propagation-1);
99}
100
101unsigned int Filter::Output(int outputSite, const byte *inString, unsigned int length, int messageEnd, bool blocking, const std::string &channel)
102{
103if (messageEnd)
104messageEnd--;
105unsigned int result = AttachedTransformation()->Put2(inString, length, messageEnd, blocking);
106m_continueAt = result ? outputSite : 0;
107return result;
108}
109
110bool Filter::OutputFlush(int outputSite, bool hardFlush, int propagation, bool blocking, const std::string &channel)
111{
112if (propagation && AttachedTransformation()->ChannelFlush(channel, hardFlush, propagation-1, blocking))
113{
114m_continueAt = outputSite;
115return true;
116}
117m_continueAt = 0;
118return false;
119}
120
121bool Filter::OutputMessageSeriesEnd(int outputSite, int propagation, bool blocking, const std::string &channel)
122{
123if (propagation && AttachedTransformation()->ChannelMessageSeriesEnd(channel, propagation-1, blocking))
124{
125m_continueAt = outputSite;
126return true;
127}
128m_continueAt = 0;
129return false;
130}
131
132// *************************************************************
133
134unsigned int MeterFilter::Put2(const byte *begin, unsigned int length, int messageEnd, bool blocking)
135{
136if (m_transparent)
137{
138FILTER_BEGIN;
139m_currentMessageBytes += length;
140m_totalBytes += length;
141
142if (messageEnd)
143{
144m_currentMessageBytes = 0;
145m_currentSeriesMessages++;
146m_totalMessages++;
147}
148
149FILTER_OUTPUT(1, begin, length, messageEnd);
150FILTER_END_NO_MESSAGE_END;
151}
152return 0;
153}
154
155bool MeterFilter::IsolatedMessageSeriesEnd(bool blocking)
156{
157m_currentMessageBytes = 0;
158m_currentSeriesMessages = 0;
159m_totalMessageSeries++;
160return false;
161}
162
163// *************************************************************
164
165void FilterWithBufferedInput::BlockQueue::ResetQueue(unsigned int blockSize, unsigned int maxBlocks)
166{
167m_buffer.New(blockSize * maxBlocks);
168m_blockSize = blockSize;
169m_maxBlocks = maxBlocks;
170m_size = 0;
171m_begin = m_buffer;
172}
173
174byte *FilterWithBufferedInput::BlockQueue::GetBlock()
175{
176if (m_size >= m_blockSize)
177{
178byte *ptr = m_begin;
179if ((m_begin+=m_blockSize) == m_buffer.end())
180m_begin = m_buffer;
181m_size -= m_blockSize;
182return ptr;
183}
184else
185return NULL;
186}
187
188byte *FilterWithBufferedInput::BlockQueue::GetContigousBlocks(unsigned int &numberOfBytes)
189{
190numberOfBytes = STDMIN(numberOfBytes, STDMIN((unsigned int)(m_buffer.end()-m_begin), m_size));
191byte *ptr = m_begin;
192m_begin += numberOfBytes;
193m_size -= numberOfBytes;
194if (m_size == 0 || m_begin == m_buffer.end())
195m_begin = m_buffer;
196return ptr;
197}
198
199unsigned int FilterWithBufferedInput::BlockQueue::GetAll(byte *outString)
200{
201unsigned int size = m_size;
202unsigned int numberOfBytes = m_maxBlocks*m_blockSize;
203const byte *ptr = GetContigousBlocks(numberOfBytes);
204memcpy(outString, ptr, numberOfBytes);
205memcpy(outString+numberOfBytes, m_begin, m_size);
206m_size = 0;
207return size;
208}
209
210void FilterWithBufferedInput::BlockQueue::Put(const byte *inString, unsigned int length)
211{
212assert(m_size + length <= m_buffer.size());
213byte *end = (m_size < (unsigned int)(m_buffer.end()-m_begin)) ? m_begin + m_size : m_begin + m_size - m_buffer.size();
214unsigned int len = STDMIN(length, (unsigned int)(m_buffer.end()-end));
215memcpy(end, inString, len);
216if (len < length)
217memcpy(m_buffer, inString+len, length-len);
218m_size += length;
219}
220
221FilterWithBufferedInput::FilterWithBufferedInput(BufferedTransformation *attachment)
222: Filter(attachment)
223{
224}
225
226FilterWithBufferedInput::FilterWithBufferedInput(unsigned int firstSize, unsigned int blockSize, unsigned int lastSize, BufferedTransformation *attachment)
227: Filter(attachment), m_firstSize(firstSize), m_blockSize(blockSize), m_lastSize(lastSize)
228, m_firstInputDone(false)
229{
230if (m_firstSize < 0 || m_blockSize < 1 || m_lastSize < 0)
231throw InvalidArgument("FilterWithBufferedInput: invalid buffer size");
232
233m_queue.ResetQueue(1, m_firstSize);
234}
235
236void FilterWithBufferedInput::IsolatedInitialize(const NameValuePairs &parameters)
237{
238InitializeDerivedAndReturnNewSizes(parameters, m_firstSize, m_blockSize, m_lastSize);
239if (m_firstSize < 0 || m_blockSize < 1 || m_lastSize < 0)
240throw InvalidArgument("FilterWithBufferedInput: invalid buffer size");
241m_queue.ResetQueue(1, m_firstSize);
242m_firstInputDone = false;
243}
244
245bool FilterWithBufferedInput::IsolatedFlush(bool hardFlush, bool blocking)
246{
247if (!blocking)
248throw BlockingInputOnly("FilterWithBufferedInput");
249
250if (hardFlush)
251ForceNextPut();
252FlushDerived();
253
254return false;
255}
256
257unsigned int FilterWithBufferedInput::PutMaybeModifiable(byte *inString, unsigned int length, int messageEnd, bool blocking, bool modifiable)
258{
259if (!blocking)
260throw BlockingInputOnly("FilterWithBufferedInput");
261
262if (length != 0)
263{
264unsigned int newLength = m_queue.CurrentSize() + length;
265
266if (!m_firstInputDone && newLength >= m_firstSize)
267{
268unsigned int len = m_firstSize - m_queue.CurrentSize();
269m_queue.Put(inString, len);
270FirstPut(m_queue.GetContigousBlocks(m_firstSize));
271assert(m_queue.CurrentSize() == 0);
272m_queue.ResetQueue(m_blockSize, (2*m_blockSize+m_lastSize-2)/m_blockSize);
273
274inString += len;
275newLength -= m_firstSize;
276m_firstInputDone = true;
277}
278
279if (m_firstInputDone)
280{
281if (m_blockSize == 1)
282{
283while (newLength > m_lastSize && m_queue.CurrentSize() > 0)
284{
285unsigned int len = newLength - m_lastSize;
286byte *ptr = m_queue.GetContigousBlocks(len);
287NextPutModifiable(ptr, len);
288newLength -= len;
289}
290
291if (newLength > m_lastSize)
292{
293unsigned int len = newLength - m_lastSize;
294NextPutMaybeModifiable(inString, len, modifiable);
295inString += len;
296newLength -= len;
297}
298}
299else
300{
301while (newLength >= m_blockSize + m_lastSize && m_queue.CurrentSize() >= m_blockSize)
302{
303NextPutModifiable(m_queue.GetBlock(), m_blockSize);
304newLength -= m_blockSize;
305}
306
307if (newLength >= m_blockSize + m_lastSize && m_queue.CurrentSize() > 0)
308{
309assert(m_queue.CurrentSize() < m_blockSize);
310unsigned int len = m_blockSize - m_queue.CurrentSize();
311m_queue.Put(inString, len);
312inString += len;
313NextPutModifiable(m_queue.GetBlock(), m_blockSize);
314newLength -= m_blockSize;
315}
316
317if (newLength >= m_blockSize + m_lastSize)
318{
319unsigned int len = RoundDownToMultipleOf(newLength - m_lastSize, m_blockSize);
320NextPutMaybeModifiable(inString, len, modifiable);
321inString += len;
322newLength -= len;
323}
324}
325}
326
327m_queue.Put(inString, newLength - m_queue.CurrentSize());
328}
329
330if (messageEnd)
331{
332if (!m_firstInputDone && m_firstSize==0)
333FirstPut(NULL);
334
335SecByteBlock temp(m_queue.CurrentSize());
336m_queue.GetAll(temp);
337LastPut(temp, temp.size());
338
339m_firstInputDone = false;
340m_queue.ResetQueue(1, m_firstSize);
341
342Output(1, NULL, 0, messageEnd, blocking);
343}
344return 0;
345}
346
347void FilterWithBufferedInput::ForceNextPut()
348{
349if (!m_firstInputDone)
350return;
351
352if (m_blockSize > 1)
353{
354while (m_queue.CurrentSize() >= m_blockSize)
355NextPutModifiable(m_queue.GetBlock(), m_blockSize);
356}
357else
358{
359unsigned int len;
360while ((len = m_queue.CurrentSize()) > 0)
361NextPutModifiable(m_queue.GetContigousBlocks(len), len);
362}
363}
364
365void FilterWithBufferedInput::NextPutMultiple(const byte *inString, unsigned int length)
366{
367assert(m_blockSize > 1);// m_blockSize = 1 should always override this function
368while (length > 0)
369{
370assert(length >= m_blockSize);
371NextPutSingle(inString);
372inString += m_blockSize;
373length -= m_blockSize;
374}
375}
376
377// *************************************************************
378
379void Redirector::ChannelInitialize(const std::string &channel, const NameValuePairs &parameters, int propagation)
380{
381if (channel.empty())
382{
383m_target = parameters.GetValueWithDefault("RedirectionTargetPointer", (BufferedTransformation*)NULL);
384m_passSignal = parameters.GetValueWithDefault("PassSignal", true);
385}
386
387if (m_target && m_passSignal)
388m_target->ChannelInitialize(channel, parameters, propagation);
389}
390
391// *************************************************************
392
393ProxyFilter::ProxyFilter(BufferedTransformation *filter, unsigned int firstSize, unsigned int lastSize, BufferedTransformation *attachment)
394: FilterWithBufferedInput(firstSize, 1, lastSize, attachment), m_filter(filter)
395{
396if (m_filter.get())
397m_filter->Attach(new OutputProxy(*this, false));
398}
399
400bool ProxyFilter::IsolatedFlush(bool hardFlush, bool blocking)
401{
402return m_filter.get() ? m_filter->Flush(hardFlush, -1, blocking) : false;
403}
404
405void ProxyFilter::SetFilter(Filter *filter)
406{
407m_filter.reset(filter);
408if (filter)
409{
410OutputProxy *proxy;
411std::auto_ptr<OutputProxy> temp(proxy = new OutputProxy(*this, false));
412m_filter->TransferAllTo(*proxy);
413m_filter->Attach(temp.release());
414}
415}
416
417void ProxyFilter::NextPutMultiple(const byte *s, unsigned int len)
418{
419if (m_filter.get())
420m_filter->Put(s, len);
421}
422
423// *************************************************************
424
425unsigned int ArraySink::Put2(const byte *begin, unsigned int length, int messageEnd, bool blocking)
426{
427memcpy(m_buf+m_total, begin, STDMIN(length, SaturatingSubtract(m_size, m_total)));
428m_total += length;
429return 0;
430}
431
432byte * ArraySink::CreatePutSpace(unsigned int &size)
433{
434size = m_size - m_total;
435return m_buf + m_total;
436}
437
438void ArraySink::IsolatedInitialize(const NameValuePairs &parameters)
439{
440ByteArrayParameter array;
441if (!parameters.GetValue(Name::OutputBuffer(), array))
442throw InvalidArgument("ArraySink: missing OutputBuffer argument");
443m_buf = array.begin();
444m_size = array.size();
445m_total = 0;
446}
447
448unsigned int ArrayXorSink::Put2(const byte *begin, unsigned int length, int messageEnd, bool blocking)
449{
450xorbuf(m_buf+m_total, begin, STDMIN(length, SaturatingSubtract(m_size, m_total)));
451m_total += length;
452return 0;
453}
454
455// *************************************************************
456
457unsigned int StreamTransformationFilter::LastBlockSize(StreamTransformation &c, BlockPaddingScheme padding)
458{
459if (c.MinLastBlockSize() > 0)
460return c.MinLastBlockSize();
461else if (c.MandatoryBlockSize() > 1 && !c.IsForwardTransformation() && padding != NO_PADDING && padding != ZEROS_PADDING)
462return c.MandatoryBlockSize();
463else
464return 0;
465}
466
467StreamTransformationFilter::StreamTransformationFilter(StreamTransformation &c, BufferedTransformation *attachment, BlockPaddingScheme padding)
468 : FilterWithBufferedInput(0, c.MandatoryBlockSize(), LastBlockSize(c, padding), attachment)
469, m_cipher(c)
470{
471assert(c.MinLastBlockSize() == 0 || c.MinLastBlockSize() > c.MandatoryBlockSize());
472
473bool isBlockCipher = (c.MandatoryBlockSize() > 1 && c.MinLastBlockSize() == 0);
474
475if (padding == DEFAULT_PADDING)
476{
477if (isBlockCipher)
478m_padding = PKCS_PADDING;
479else
480m_padding = NO_PADDING;
481}
482else
483m_padding = padding;
484
485if (!isBlockCipher && (m_padding == PKCS_PADDING || m_padding == ONE_AND_ZEROS_PADDING))
486throw InvalidArgument("StreamTransformationFilter: PKCS_PADDING and ONE_AND_ZEROS_PADDING cannot be used with " + c.AlgorithmName());
487}
488
489void StreamTransformationFilter::FirstPut(const byte *inString)
490{
491m_optimalBufferSize = m_cipher.OptimalBlockSize();
492m_optimalBufferSize = STDMAX(m_optimalBufferSize, RoundDownToMultipleOf(4096U, m_optimalBufferSize));
493}
494
495void StreamTransformationFilter::NextPutMultiple(const byte *inString, unsigned int length)
496{
497if (!length)
498return;
499
500unsigned int s = m_cipher.MandatoryBlockSize();
501
502do
503{
504unsigned int len = m_optimalBufferSize;
505byte *space = HelpCreatePutSpace(*AttachedTransformation(), NULL_CHANNEL, s, length, len);
506if (len < length)
507{
508if (len == m_optimalBufferSize)
509len -= m_cipher.GetOptimalBlockSizeUsed();
510len = RoundDownToMultipleOf(len, s);
511}
512else
513len = length;
514m_cipher.ProcessString(space, inString, len);
515AttachedTransformation()->PutModifiable(space, len);
516inString += len;
517length -= len;
518}
519while (length > 0);
520}
521
522void StreamTransformationFilter::NextPutModifiable(byte *inString, unsigned int length)
523{
524m_cipher.ProcessString(inString, length);
525AttachedTransformation()->PutModifiable(inString, length);
526}
527
528void StreamTransformationFilter::LastPut(const byte *inString, unsigned int length)
529{
530byte *space = NULL;
531
532switch (m_padding)
533{
534case NO_PADDING:
535case ZEROS_PADDING:
536if (length > 0)
537{
538unsigned int minLastBlockSize = m_cipher.MinLastBlockSize();
539bool isForwardTransformation = m_cipher.IsForwardTransformation();
540
541if (isForwardTransformation && m_padding == ZEROS_PADDING && (minLastBlockSize == 0 || length < minLastBlockSize))
542{
543// do padding
544unsigned int blockSize = STDMAX(minLastBlockSize, m_cipher.MandatoryBlockSize());
545space = HelpCreatePutSpace(*AttachedTransformation(), NULL_CHANNEL, blockSize);
546memcpy(space, inString, length);
547memset(space + length, 0, blockSize - length);
548m_cipher.ProcessLastBlock(space, space, blockSize);
549AttachedTransformation()->Put(space, blockSize);
550}
551else
552{
553if (minLastBlockSize == 0)
554{
555if (isForwardTransformation)
556throw InvalidDataFormat("StreamTransformationFilter: plaintext length is not a multiple of block size and NO_PADDING is specified");
557else
558throw InvalidCiphertext("StreamTransformationFilter: ciphertext length is not a multiple of block size");
559}
560
561space = HelpCreatePutSpace(*AttachedTransformation(), NULL_CHANNEL, length, m_optimalBufferSize);
562m_cipher.ProcessLastBlock(space, inString, length);
563AttachedTransformation()->Put(space, length);
564}
565}
566break;
567
568case PKCS_PADDING:
569case ONE_AND_ZEROS_PADDING:
570unsigned int s;
571s = m_cipher.MandatoryBlockSize();
572assert(s > 1);
573space = HelpCreatePutSpace(*AttachedTransformation(), NULL_CHANNEL, s, m_optimalBufferSize);
574if (m_cipher.IsForwardTransformation())
575{
576assert(length < s);
577memcpy(space, inString, length);
578if (m_padding == PKCS_PADDING)
579{
580assert(s < 256);
581byte pad = s-length;
582memset(space+length, pad, s-length);
583}
584else
585{
586space[length] = 1;
587memset(space+length+1, 0, s-length-1);
588}
589m_cipher.ProcessData(space, space, s);
590AttachedTransformation()->Put(space, s);
591}
592else
593{
594if (length != s)
595throw InvalidCiphertext("StreamTransformationFilter: ciphertext length is not a multiple of block size");
596m_cipher.ProcessData(space, inString, s);
597if (m_padding == PKCS_PADDING)
598{
599byte pad = space[s-1];
600if (pad < 1 || pad > s || std::find_if(space+s-pad, space+s, std::bind2nd(std::not_equal_to<byte>(), pad)) != space+s)
601throw InvalidCiphertext("StreamTransformationFilter: invalid PKCS #7 block padding found");
602length = s-pad;
603}
604else
605{
606while (length > 1 && space[length-1] == '\0')
607--length;
608if (space[--length] != '\1')
609throw InvalidCiphertext("StreamTransformationFilter: invalid ones-and-zeros padding found");
610}
611AttachedTransformation()->Put(space, length);
612}
613break;
614
615default:
616assert(false);
617}
618}
619
620// *************************************************************
621
622void HashFilter::IsolatedInitialize(const NameValuePairs &parameters)
623{
624m_putMessage = parameters.GetValueWithDefault(Name::PutMessage(), false);
625m_hashModule.Restart();
626}
627
628unsigned int HashFilter::Put2(const byte *inString, unsigned int length, int messageEnd, bool blocking)
629{
630FILTER_BEGIN;
631m_hashModule.Update(inString, length);
632if (m_putMessage)
633FILTER_OUTPUT(1, inString, length, 0);
634if (messageEnd)
635{
636{
637unsigned int size, digestSize = m_hashModule.DigestSize();
638m_space = HelpCreatePutSpace(*AttachedTransformation(), NULL_CHANNEL, digestSize, digestSize, size = digestSize);
639m_hashModule.Final(m_space);
640}
641FILTER_OUTPUT(2, m_space, m_hashModule.DigestSize(), messageEnd);
642}
643FILTER_END_NO_MESSAGE_END;
644}
645
646// *************************************************************
647
648HashVerificationFilter::HashVerificationFilter(HashTransformation &hm, BufferedTransformation *attachment, word32 flags)
649: FilterWithBufferedInput(attachment)
650, m_hashModule(hm)
651{
652IsolatedInitialize(MakeParameters(Name::HashVerificationFilterFlags(), flags));
653}
654
655void HashVerificationFilter::InitializeDerivedAndReturnNewSizes(const NameValuePairs &parameters, unsigned int &firstSize, unsigned int &blockSize, unsigned int &lastSize)
656{
657m_flags = parameters.GetValueWithDefault(Name::HashVerificationFilterFlags(), (word32)DEFAULT_FLAGS);
658m_hashModule.Restart();
659unsigned int size = m_hashModule.DigestSize();
660m_verified = false;
661firstSize = m_flags & HASH_AT_BEGIN ? size : 0;
662blockSize = 1;
663lastSize = m_flags & HASH_AT_BEGIN ? 0 : size;
664}
665
666void HashVerificationFilter::FirstPut(const byte *inString)
667{
668if (m_flags & HASH_AT_BEGIN)
669{
670m_expectedHash.New(m_hashModule.DigestSize());
671memcpy(m_expectedHash, inString, m_expectedHash.size());
672if (m_flags & PUT_HASH)
673AttachedTransformation()->Put(inString, m_expectedHash.size());
674}
675}
676
677void HashVerificationFilter::NextPutMultiple(const byte *inString, unsigned int length)
678{
679m_hashModule.Update(inString, length);
680if (m_flags & PUT_MESSAGE)
681AttachedTransformation()->Put(inString, length);
682}
683
684void HashVerificationFilter::LastPut(const byte *inString, unsigned int length)
685{
686if (m_flags & HASH_AT_BEGIN)
687{
688assert(length == 0);
689m_verified = m_hashModule.Verify(m_expectedHash);
690}
691else
692{
693m_verified = (length==m_hashModule.DigestSize() && m_hashModule.Verify(inString));
694if (m_flags & PUT_HASH)
695AttachedTransformation()->Put(inString, length);
696}
697
698if (m_flags & PUT_RESULT)
699AttachedTransformation()->Put(m_verified);
700
701if ((m_flags & THROW_EXCEPTION) && !m_verified)
702throw HashVerificationFailed();
703}
704
705// *************************************************************
706
707void SignerFilter::IsolatedInitialize(const NameValuePairs &parameters)
708{
709m_putMessage = parameters.GetValueWithDefault(Name::PutMessage(), false);
710m_messageAccumulator.reset(m_signer.NewSignatureAccumulator());
711}
712
713unsigned int SignerFilter::Put2(const byte *inString, unsigned int length, int messageEnd, bool blocking)
714{
715FILTER_BEGIN;
716m_messageAccumulator->Update(inString, length);
717if (m_putMessage)
718FILTER_OUTPUT(1, inString, length, 0);
719if (messageEnd)
720{
721m_buf.New(m_signer.SignatureLength());
722m_signer.Sign(m_rng, m_messageAccumulator.release(), m_buf);
723FILTER_OUTPUT(2, m_buf, m_buf.size(), messageEnd);
724m_messageAccumulator.reset(m_signer.NewSignatureAccumulator());
725}
726FILTER_END_NO_MESSAGE_END;
727}
728
729SignatureVerificationFilter::SignatureVerificationFilter(const PK_Verifier &verifier, BufferedTransformation *attachment, word32 flags)
730: FilterWithBufferedInput(attachment)
731, m_verifier(verifier)
732{
733IsolatedInitialize(MakeParameters(Name::SignatureVerificationFilterFlags(), flags));
734}
735
736void SignatureVerificationFilter::InitializeDerivedAndReturnNewSizes(const NameValuePairs &parameters, unsigned int &firstSize, unsigned int &blockSize, unsigned int &lastSize)
737{
738m_flags = parameters.GetValueWithDefault(Name::SignatureVerificationFilterFlags(), (word32)DEFAULT_FLAGS);
739m_messageAccumulator.reset(m_verifier.NewVerificationAccumulator());
740unsigned int size =m_verifier.SignatureLength();
741assert(size != 0);// TODO: handle recoverable signature scheme
742m_verified = false;
743firstSize = m_flags & SIGNATURE_AT_BEGIN ? size : 0;
744blockSize = 1;
745lastSize = m_flags & SIGNATURE_AT_BEGIN ? 0 : size;
746}
747
748void SignatureVerificationFilter::FirstPut(const byte *inString)
749{
750if (m_flags & SIGNATURE_AT_BEGIN)
751{
752if (m_verifier.SignatureUpfront())
753m_verifier.InputSignature(*m_messageAccumulator, inString, m_verifier.SignatureLength());
754else
755{
756m_signature.New(m_verifier.SignatureLength());
757memcpy(m_signature, inString, m_signature.size());
758}
759
760if (m_flags & PUT_SIGNATURE)
761AttachedTransformation()->Put(inString, m_signature.size());
762}
763else
764{
765assert(!m_verifier.SignatureUpfront());
766}
767}
768
769void SignatureVerificationFilter::NextPutMultiple(const byte *inString, unsigned int length)
770{
771m_messageAccumulator->Update(inString, length);
772if (m_flags & PUT_MESSAGE)
773AttachedTransformation()->Put(inString, length);
774}
775
776void SignatureVerificationFilter::LastPut(const byte *inString, unsigned int length)
777{
778if (m_flags & SIGNATURE_AT_BEGIN)
779{
780assert(length == 0);
781m_verifier.InputSignature(*m_messageAccumulator, m_signature, m_signature.size());
782m_verified = m_verifier.VerifyAndRestart(*m_messageAccumulator);
783}
784else
785{
786m_verifier.InputSignature(*m_messageAccumulator, inString, length);
787m_verified = m_verifier.VerifyAndRestart(*m_messageAccumulator);
788if (m_flags & PUT_SIGNATURE)
789AttachedTransformation()->Put(inString, length);
790}
791
792if (m_flags & PUT_RESULT)
793AttachedTransformation()->Put(m_verified);
794
795if ((m_flags & THROW_EXCEPTION) && !m_verified)
796throw SignatureVerificationFailed();
797}
798
799// *************************************************************
800
801unsigned int Source::PumpAll2(bool blocking)
802{
803// TODO: switch length type
804unsigned long i = UINT_MAX;
805RETURN_IF_NONZERO(Pump2(i, blocking));
806unsigned int j = UINT_MAX;
807return PumpMessages2(j, blocking);
808}
809
810bool Store::GetNextMessage()
811{
812if (!m_messageEnd && !AnyRetrievable())
813{
814m_messageEnd=true;
815return true;
816}
817else
818return false;
819}
820
821unsigned int Store::CopyMessagesTo(BufferedTransformation &target, unsigned int count, const std::string &channel) const
822{
823if (m_messageEnd || count == 0)
824return 0;
825else
826{
827CopyTo(target, ULONG_MAX, channel);
828if (GetAutoSignalPropagation())
829target.ChannelMessageEnd(channel, GetAutoSignalPropagation()-1);
830return 1;
831}
832}
833
834void StringStore::StoreInitialize(const NameValuePairs &parameters)
835{
836ConstByteArrayParameter array;
837if (!parameters.GetValue(Name::InputBuffer(), array))
838throw InvalidArgument("StringStore: missing InputBuffer argument");
839m_store = array.begin();
840m_length = array.size();
841m_count = 0;
842}
843
844unsigned int StringStore::TransferTo2(BufferedTransformation &target, unsigned long &transferBytes, const std::string &channel, bool blocking)
845{
846unsigned long position = 0;
847unsigned int blockedBytes = CopyRangeTo2(target, position, transferBytes, channel, blocking);
848m_count += position;
849transferBytes = position;
850return blockedBytes;
851}
852
853unsigned int StringStore::CopyRangeTo2(BufferedTransformation &target, unsigned long &begin, unsigned long end, const std::string &channel, bool blocking) const
854{
855unsigned int i = (unsigned int)STDMIN((unsigned long)m_count+begin, (unsigned long)m_length);
856unsigned int len = (unsigned int)STDMIN((unsigned long)m_length-i, end-begin);
857unsigned int blockedBytes = target.ChannelPut2(channel, m_store+i, len, 0, blocking);
858if (!blockedBytes)
859begin += len;
860return blockedBytes;
861}
862
863unsigned int RandomNumberStore::TransferTo2(BufferedTransformation &target, unsigned long &transferBytes, const std::string &channel, bool blocking)
864{
865if (!blocking)
866throw NotImplemented("RandomNumberStore: nonblocking transfer is not implemented by this object");
867
868unsigned long transferMax = transferBytes;
869for (transferBytes = 0; transferBytes<transferMax && m_count < m_length; ++transferBytes, ++m_count)
870target.ChannelPut(channel, m_rng.GenerateByte());
871return 0;
872}
873
874unsigned int NullStore::CopyRangeTo2(BufferedTransformation &target, unsigned long &begin, unsigned long end, const std::string &channel, bool blocking) const
875{
876static const byte nullBytes[128] = {0};
877while (begin < end)
878{
879unsigned int len = STDMIN(end-begin, 128UL);
880unsigned int blockedBytes = target.ChannelPut2(channel, nullBytes, len, 0, blocking);
881if (blockedBytes)
882return blockedBytes;
883begin += len;
884}
885return 0;
886}
887
888unsigned int NullStore::TransferTo2(BufferedTransformation &target, unsigned long &transferBytes, const std::string &channel, bool blocking)
889{
890unsigned long begin = 0;
891unsigned int blockedBytes = NullStore::CopyRangeTo2(target, begin, transferBytes, channel, blocking);
892transferBytes = begin;
893m_size -= begin;
894return blockedBytes;
895}
896
897NAMESPACE_END

Archive Download this file

Branches

Tags

Quick Links:     www.monotone.ca    -     Downloads    -     Documentation    -     Wiki    -     Code Forge    -     Build Status