Esempio n. 1
0
 public void Run()
 {
     try
     {
         MockTlsServer     server         = new MockTlsServer();
         TlsServerProtocol serverProtocol = new TlsServerProtocol(s.GetStream(), secureRandom);
         serverProtocol.Accept(server);
         Stream log = new TeeOutputStream(serverProtocol.Stream, stdout);
         Streams.PipeAll(serverProtocol.Stream, log);
         serverProtocol.Close();
     }
     finally
     {
         try
         {
             s.Close();
         }
         catch (IOException)
         {
         }
         finally
         {
         }
     }
 }
    private CmsAuthenticatedData Generate(CmsProcessable content, string macOid, CipherKeyGenerator keyGen)
    {
        KeyParameter        keyParameter;
        AlgorithmIdentifier algorithmIdentifier;
        Asn1OctetString     content2;
        Asn1OctetString     mac2;

        try
        {
            byte[] array = keyGen.GenerateKey();
            keyParameter = ParameterUtilities.CreateKeyParameter(macOid, array);
            Asn1Encodable asn1Params = GenerateAsn1Parameters(macOid, array);
            algorithmIdentifier = GetAlgorithmIdentifier(macOid, keyParameter, asn1Params, out ICipherParameters _);
            IMac mac = MacUtilities.GetMac(macOid);
            mac.Init(keyParameter);
            MemoryStream memoryStream = new MemoryStream();
            Stream       stream       = new TeeOutputStream(memoryStream, new MacOutputStream(mac));
            content.Write(stream);
            Platform.Dispose(stream);
            content2 = new BerOctetString(memoryStream.ToArray());
            byte[] str = MacUtilities.DoFinal(mac);
            mac2 = new DerOctetString(str);
        }
        catch (SecurityUtilityException e)
        {
            throw new CmsException("couldn't create cipher.", e);
        }
        catch (InvalidKeyException e2)
        {
            throw new CmsException("key invalid in message.", e2);
        }
        catch (IOException e3)
        {
            throw new CmsException("exception decoding algorithm parameters.", e3);
        }
        Asn1EncodableVector asn1EncodableVector = new Asn1EncodableVector();

        foreach (RecipientInfoGenerator recipientInfoGenerator in recipientInfoGenerators)
        {
            try
            {
                asn1EncodableVector.Add(recipientInfoGenerator.Generate(keyParameter, rand));
            }
            catch (InvalidKeyException e4)
            {
                throw new CmsException("key inappropriate for algorithm.", e4);
            }
            catch (GeneralSecurityException e5)
            {
                throw new CmsException("error making encrypted content.", e5);
            }
        }
        ContentInfo encapsulatedContent = new ContentInfo(CmsObjectIdentifiers.Data, content2);
        ContentInfo contentInfo         = new ContentInfo(CmsObjectIdentifiers.AuthenticatedData, new AuthenticatedData(null, new DerSet(asn1EncodableVector), algorithmIdentifier, null, encapsulatedContent, null, mac2, null));

        return(new CmsAuthenticatedData(contentInfo));
    }
        public void ReceiveStream(Stream streamFromSender)
        {
            Console.WriteLine("Forwarding the stream...");

            try
            {
                //PipeStream: http://www.codeproject.com/Articles/16011/PipeStream-a-Memory-Efficient-and-Thread-Safe-Stre
                //redirecting the output of one process to the input of another in the command line without using any intermediate data storage.
                var pipeToReceiver = new PipeStream();

                //setup a pipe between forwarder (this) and receiver - for now the pipe is still empty
                //ASYNC
                var forwardingTask = Task.Factory.StartNew(() => ForwardStream(pipeToReceiver));

                Directory.CreateDirectory("forwarder");
                var outputFileStream = File.OpenWrite(@"forwarder\received-compressed-file.rar");
                var teeCache         = new TeeOutputStream(outputFileStream, pipeToReceiver);
                var tee = new TeeInputStream(streamFromSender, teeCache, true);

                DecompressStream(tee);

                Console.WriteLine("Copied .RAR locally + extracted .RAR!");

                //pipeToReceiver cannot be closed because it can still contain data to be processed at the receiver's end
                teeCache.Flush(); //flushes both streams
                Console.WriteLine("Pipe to receiver flushed...");

                tee.Close(); //closes primary and secondary stream (autoClose = true) ; secondary stream => will only close outputFileStream (autoClose = false)

                //wait untill all bytes from input are transferred to the receiver
                forwardingTask.Wait();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }

            Console.WriteLine("Stream successfully forwarded!");
        }
 protected Stream Open(Stream outStr, AlgorithmIdentifier macAlgId, ICipherParameters cipherParameters, Asn1EncodableVector recipientInfos)
 {
     try
     {
         BerSequenceGenerator berSequenceGenerator = new BerSequenceGenerator(outStr);
         berSequenceGenerator.AddObject(CmsObjectIdentifiers.AuthenticatedData);
         BerSequenceGenerator berSequenceGenerator2 = new BerSequenceGenerator(berSequenceGenerator.GetRawOutputStream(), 0, isExplicit: true);
         berSequenceGenerator2.AddObject(new DerInteger(AuthenticatedData.CalculateVersion(null)));
         Stream        rawOutputStream = berSequenceGenerator2.GetRawOutputStream();
         Asn1Generator asn1Generator   = _berEncodeRecipientSet ? ((Asn1Generator) new BerSetGenerator(rawOutputStream)) : ((Asn1Generator) new DerSetGenerator(rawOutputStream));
         foreach (Asn1Encodable recipientInfo in recipientInfos)
         {
             asn1Generator.AddObject(recipientInfo);
         }
         asn1Generator.Close();
         berSequenceGenerator2.AddObject(macAlgId);
         BerSequenceGenerator berSequenceGenerator3 = new BerSequenceGenerator(rawOutputStream);
         berSequenceGenerator3.AddObject(CmsObjectIdentifiers.Data);
         Stream output = CmsUtilities.CreateBerOctetOutputStream(berSequenceGenerator3.GetRawOutputStream(), 0, isExplicit: false, _bufferSize);
         IMac   mac    = MacUtilities.GetMac(macAlgId.Algorithm);
         mac.Init(cipherParameters);
         Stream macStream = new TeeOutputStream(output, new MacOutputStream(mac));
         return(new CmsAuthenticatedDataOutputStream(macStream, mac, berSequenceGenerator, berSequenceGenerator2, berSequenceGenerator3));
     }
     catch (SecurityUtilityException e)
     {
         throw new CmsException("couldn't create cipher.", e);
     }
     catch (InvalidKeyException e2)
     {
         throw new CmsException("key invalid in message.", e2);
     }
     catch (IOException e3)
     {
         throw new CmsException("exception decoding algorithm parameters.", e3);
     }
 }
		protected Stream Open(
			Stream        			outStr,
			AlgorithmIdentifier		macAlgId,
			ICipherParameters		cipherParameters,
			Asn1EncodableVector		recipientInfos)
		{
			try
			{
				//
				// ContentInfo
				//
				BerSequenceGenerator cGen = new BerSequenceGenerator(outStr);

				cGen.AddObject(CmsObjectIdentifiers.AuthenticatedData);

				//
				// Authenticated Data
				//
				BerSequenceGenerator authGen = new BerSequenceGenerator(
					cGen.GetRawOutputStream(), 0, true);

				authGen.AddObject(new DerInteger(AuthenticatedData.CalculateVersion(null)));

				Stream authRaw = authGen.GetRawOutputStream();
				Asn1Generator recipGen = _berEncodeRecipientSet
					?	(Asn1Generator) new BerSetGenerator(authRaw)
					:	new DerSetGenerator(authRaw);

				foreach (Asn1Encodable ae in recipientInfos)
				{
					recipGen.AddObject(ae);
				}

				recipGen.Close();

				authGen.AddObject(macAlgId);

				BerSequenceGenerator eiGen = new BerSequenceGenerator(authRaw);
				eiGen.AddObject(CmsObjectIdentifiers.Data);

				Stream octetOutputStream = CmsUtilities.CreateBerOctetOutputStream(
					eiGen.GetRawOutputStream(), 0, false, _bufferSize);

				IMac mac = MacUtilities.GetMac(macAlgId.ObjectID);
				// TODO Confirm no ParametersWithRandom needed
	            mac.Init(cipherParameters);
				Stream mOut = new TeeOutputStream(octetOutputStream, new MacOutputStream(mac));

				return new CmsAuthenticatedDataOutputStream(mOut, mac, cGen, authGen, eiGen);
			}
			catch (SecurityUtilityException e)
			{
				throw new CmsException("couldn't create cipher.", e);
			}
			catch (InvalidKeyException e)
			{
				throw new CmsException("key invalid in message.", e);
			}
			catch (IOException e)
			{
				throw new CmsException("exception decoding algorithm parameters.", e);
			}
		}
		/**
		* generate a signed object that for a CMS Signed Data
		* object using the given provider - if encapsulate is true a copy
		* of the message will be included in the signature. The content type
		* is set according to the OID represented by the string signedContentType.
		* @param out stream the CMS object is to be written to.
		* @param signedContentType OID for data to be signed.
		* @param encapsulate true if data should be encapsulated.
		* @param dataOutputStream output stream to copy the data being signed to.
		*/
		public Stream Open(
			Stream	outStream,
			string	signedContentType,
			bool	encapsulate,
			Stream	dataOutputStream)
		{
			if (outStream == null)
				throw new ArgumentNullException("outStream");
			if (!outStream.CanWrite)
				throw new ArgumentException("Expected writeable stream", "outStream");
			if (dataOutputStream != null && !dataOutputStream.CanWrite)
				throw new ArgumentException("Expected writeable stream", "dataOutputStream");

			_messageDigestsLocked = true;
			
			//
            // ContentInfo
            //
            BerSequenceGenerator sGen = new BerSequenceGenerator(outStream);

			sGen.AddObject(CmsObjectIdentifiers.SignedData);

			//
            // Signed Data
            //
            BerSequenceGenerator sigGen = new BerSequenceGenerator(
				sGen.GetRawOutputStream(), 0, true);

			sigGen.AddObject(CalculateVersion(signedContentType));

			Asn1EncodableVector digestAlgs = new Asn1EncodableVector();

			foreach (string digestOid in _messageDigestOids)
            {
				digestAlgs.Add(
            		new AlgorithmIdentifier(new DerObjectIdentifier(digestOid), DerNull.Instance));
            }

            {
				byte[] tmp = new DerSet(digestAlgs).GetEncoded();
				sigGen.GetRawOutputStream().Write(tmp, 0, tmp.Length);
			}

			BerSequenceGenerator eiGen = new BerSequenceGenerator(sigGen.GetRawOutputStream());

			eiGen.AddObject(new DerObjectIdentifier(signedContentType));

			Stream digStream;
			if (encapsulate)
            {
                BerOctetStringGenerator octGen = new BerOctetStringGenerator(
					eiGen.GetRawOutputStream(), 0, true);

				digStream = octGen.GetOctetOutputStream(_bufferSize);

				if (dataOutputStream != null)
				{
					digStream = new TeeOutputStream(dataOutputStream, digStream);
				}
            }
            else
            {
				if (dataOutputStream != null)
				{
					digStream = dataOutputStream;
				}
				else
				{
					digStream = new NullOutputStream();
				}
			}

			foreach (IDigest d in _messageDigests.Values)
			{
                digStream = new DigestStream(digStream, null, d);
            }

			return new CmsSignedDataOutputStream(this, digStream, signedContentType, sGen, sigGen, eiGen);
        }
	    /**
	     * generate an enveloped object that contains an CMS Enveloped Data
	     * object using the given provider and the passed in key generator.
	     */
		private CmsAuthenticatedData Generate(
			CmsProcessable		content,
			string				macOid,
			CipherKeyGenerator	keyGen)
		{
			AlgorithmIdentifier macAlgId;
			KeyParameter encKey;
			Asn1OctetString encContent;
			Asn1OctetString macResult;

			try
			{
				// FIXME Will this work for macs?
				byte[] encKeyBytes = keyGen.GenerateKey();
				encKey = ParameterUtilities.CreateKeyParameter(macOid, encKeyBytes);

				Asn1Encodable asn1Params = GenerateAsn1Parameters(macOid, encKeyBytes);

				ICipherParameters cipherParameters;
				macAlgId = GetAlgorithmIdentifier(
				macOid, encKey, asn1Params, out cipherParameters);

				IMac mac = MacUtilities.GetMac(macOid);
				// TODO Confirm no ParametersWithRandom needed
				// FIXME Only passing key at the moment
//	            mac.Init(cipherParameters);
				mac.Init(encKey);

				MemoryStream bOut = new MemoryStream();
				Stream mOut = new TeeOutputStream(bOut, new MacOutputStream(mac));

				content.Write(mOut);

				mOut.Close();
				bOut.Close();

				encContent = new BerOctetString(bOut.ToArray());

				byte[] macOctets = MacUtilities.DoFinal(mac);
				macResult = new DerOctetString(macOctets);
			}
			catch (SecurityUtilityException e)
			{
				throw new CmsException("couldn't create cipher.", e);
			}
			catch (InvalidKeyException e)
			{
				throw new CmsException("key invalid in message.", e);
			}
			catch (IOException e)
			{
				throw new CmsException("exception decoding algorithm parameters.", e);
			}

			Asn1EncodableVector recipientInfos = new Asn1EncodableVector();

			foreach (RecipientInfoGenerator rig in recipientInfoGenerators) 
			{
				try
				{
					recipientInfos.Add(rig.Generate(encKey, rand));
				}
				catch (InvalidKeyException e)
				{
					throw new CmsException("key inappropriate for algorithm.", e);
				}
				catch (GeneralSecurityException e)
				{
					throw new CmsException("error making encrypted content.", e);
				}
			}
			
			ContentInfo eci = new ContentInfo(CmsObjectIdentifiers.Data, encContent);
			
			ContentInfo contentInfo = new ContentInfo(
			CmsObjectIdentifiers.AuthenticatedData,
			new AuthenticatedData(null, new DerSet(recipientInfos), macAlgId, null, eci, null, macResult, null));
			
			return new CmsAuthenticatedData(contentInfo);
		}
        protected Stream Open(
            Stream outStr,
            AlgorithmIdentifier macAlgId,
            ICipherParameters cipherParameters,
            Asn1EncodableVector recipientInfos)
        {
            try
            {
                //
                // ContentInfo
                //
                BerSequenceGenerator cGen = new BerSequenceGenerator(outStr);

                cGen.AddObject(CmsObjectIdentifiers.AuthenticatedData);

                //
                // Authenticated Data
                //
                BerSequenceGenerator authGen = new BerSequenceGenerator(
                    cGen.GetRawOutputStream(), 0, true);

                authGen.AddObject(new DerInteger(AuthenticatedData.CalculateVersion(null)));

                Stream        authRaw  = authGen.GetRawOutputStream();
                Asn1Generator recipGen = _berEncodeRecipientSet
                                        ?       (Asn1Generator) new BerSetGenerator(authRaw)
                                        :       new DerSetGenerator(authRaw);

                foreach (Asn1Encodable ae in recipientInfos)
                {
                    recipGen.AddObject(ae);
                }

                recipGen.Close();

                authGen.AddObject(macAlgId);

                BerSequenceGenerator eiGen = new BerSequenceGenerator(authRaw);
                eiGen.AddObject(CmsObjectIdentifiers.Data);

                Stream octetOutputStream = CmsUtilities.CreateBerOctetOutputStream(
                    eiGen.GetRawOutputStream(), 0, false, _bufferSize);

                IMac mac = MacUtilities.GetMac(macAlgId.Algorithm);
                // TODO Confirm no ParametersWithRandom needed
                mac.Init(cipherParameters);
                Stream mOut = new TeeOutputStream(octetOutputStream, new MacSink(mac));

                return(new CmsAuthenticatedDataOutputStream(mOut, mac, cGen, authGen, eiGen));
            }
            catch (SecurityUtilityException e)
            {
                throw new CmsException("couldn't create cipher.", e);
            }
            catch (InvalidKeyException e)
            {
                throw new CmsException("key invalid in message.", e);
            }
            catch (IOException e)
            {
                throw new CmsException("exception decoding algorithm parameters.", e);
            }
        }
Esempio n. 9
0
        /**
         * generate an enveloped object that contains an CMS Enveloped Data
         * object using the given provider and the passed in key generator.
         */
        private CmsAuthenticatedData Generate(
            CmsProcessable content,
            string macOid,
            CipherKeyGenerator keyGen)
        {
            AlgorithmIdentifier macAlgId;
            KeyParameter        encKey;
            Asn1OctetString     encContent;
            Asn1OctetString     macResult;

            try
            {
                // FIXME Will this work for macs?
                byte[] encKeyBytes = keyGen.GenerateKey();
                encKey = ParameterUtilities.CreateKeyParameter(macOid, encKeyBytes);

                Asn1Encodable asn1Params = GenerateAsn1Parameters(macOid, encKeyBytes);

                ICipherParameters cipherParameters;
                macAlgId = GetAlgorithmIdentifier(
                    macOid, encKey, asn1Params, out cipherParameters);

                IMac mac = MacUtilities.GetMac(macOid);
                // TODO Confirm no ParametersWithRandom needed
                // FIXME Only passing key at the moment
//	            mac.Init(cipherParameters);
                mac.Init(encKey);

                MemoryStream bOut = new MemoryStream();
                Stream       mOut = new TeeOutputStream(bOut, new MacOutputStream(mac));

                content.Write(mOut);

                mOut.Close();
                bOut.Close();

                encContent = new BerOctetString(bOut.ToArray());

                byte[] macOctets = MacUtilities.DoFinal(mac);
                macResult = new DerOctetString(macOctets);
            }
            catch (SecurityUtilityException e)
            {
                throw new CmsException("couldn't create cipher.", e);
            }
            catch (InvalidKeyException e)
            {
                throw new CmsException("key invalid in message.", e);
            }
            catch (IOException e)
            {
                throw new CmsException("exception decoding algorithm parameters.", e);
            }

            Asn1EncodableVector recipientInfos = new Asn1EncodableVector();

            foreach (RecipientInfoGenerator rig in recipientInfoGenerators)
            {
                try
                {
                    recipientInfos.Add(rig.Generate(encKey, rand));
                }
                catch (InvalidKeyException e)
                {
                    throw new CmsException("key inappropriate for algorithm.", e);
                }
                catch (GeneralSecurityException e)
                {
                    throw new CmsException("error making encrypted content.", e);
                }
            }

            ContentInfo eci = new ContentInfo(CmsObjectIdentifiers.Data, encContent);

            ContentInfo contentInfo = new ContentInfo(
                CmsObjectIdentifiers.AuthenticatedData,
                new AuthenticatedData(null, new DerSet(recipientInfos), macAlgId, null, eci, null, macResult, null));

            return(new CmsAuthenticatedData(contentInfo));
        }