static void Main (string[] args)
         {
             AsymmetricKeyParameter key;
 
             using (var stream = File.OpenRead ("private-key.pem")) {
                 using (var reader = new StreamReader (stream)) {
                     var pem = new PemReader (reader);
 
                     var keyObject = pem.ReadObject ();
 
                     if (keyObject is AsymmetricCipherKeyPair pair) {
                         key = pair.Private;
                     } else if (keyObject is AsymmetricKeyParameter) {
                         key = (AsymmetricKeyParameter) keyObject;
                     }
                 }
             }
 
             var encryptedData = File.ReadAllBytes (args[0]);
             var parser = new CmsEnvelopedDataParser (encryptedData);
 			var recipients = parser.GetRecipientInfos ();
             byte[] decryptedData;
 
             foreach (RecipientInformation recipient in recipients.GetRecipients ()) {
 				decryptedData = recipient.GetContent (key);
                 break;
 			}
 
             // now you can do whatever you want with the decrypted data
         }
Ejemplo n.º 2
0
        /// <summary>
        /// Decrypt the specified encryptedData.
        /// </summary>
        /// <remarks>
        /// Decrypts the specified encryptedData.
        /// </remarks>
        /// <returns>The decrypted <see cref="MimeKit.MimeEntity"/>.</returns>
        /// <param name="encryptedData">The encrypted data.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <exception cref="System.ArgumentNullException">
        /// <paramref name="encryptedData"/> is <c>null</c>.
        /// </exception>
        /// <exception cref="Org.BouncyCastle.Cms.CmsException">
        /// An error occurred in the cryptographic message syntax subsystem.
        /// </exception>
        /// <exception cref="System.OperationCanceledException">
        /// The operation was cancelled via the cancellation token.
        /// </exception>
        public override MimeEntity Decrypt(Stream encryptedData, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (encryptedData == null)
            {
                throw new ArgumentNullException(nameof(encryptedData));
            }

            var parser     = new CmsEnvelopedDataParser(encryptedData);
            var recipients = parser.GetRecipientInfos();
            var algorithm  = parser.EncryptionAlgorithmID;
            AsymmetricKeyParameter key;

            foreach (RecipientInformation recipient in recipients.GetRecipients())
            {
                if ((key = GetPrivateKey(recipient.RecipientID)) == null)
                {
                    continue;
                }

                var content = recipient.GetContent(key);
                var memory  = new MemoryStream(content, false);

                return(MimeEntity.Load(memory, true, cancellationToken));
            }

            throw new CmsException("A suitable private key could not be found for decrypting.");
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Decrypt the specified encryptedData to an output stream.
        /// </summary>
        /// <remarks>
        /// Decrypts the specified encryptedData to an output stream.
        /// </remarks>
        /// <param name="encryptedData">The encrypted data.</param>
        /// <param name="decryptedData">The output stream.</param>
        /// <exception cref="System.ArgumentNullException">
        /// <para><paramref name="encryptedData"/> is <c>null</c>.</para>
        /// <para>-or-</para>
        /// <para><paramref name="decryptedData"/> is <c>null</c>.</para>
        /// </exception>
        /// <exception cref="Org.BouncyCastle.Cms.CmsException">
        /// An error occurred in the cryptographic message syntax subsystem.
        /// </exception>
        public override void DecryptTo(Stream encryptedData, Stream decryptedData)
        {
            if (encryptedData == null)
            {
                throw new ArgumentNullException(nameof(encryptedData));
            }

            if (decryptedData == null)
            {
                throw new ArgumentNullException(nameof(decryptedData));
            }

            var parser     = new CmsEnvelopedDataParser(encryptedData);
            var recipients = parser.GetRecipientInfos();
            var algorithm  = parser.EncryptionAlgorithmID;
            AsymmetricKeyParameter key;

            foreach (RecipientInformation recipient in recipients.GetRecipients())
            {
                if ((key = GetPrivateKey(recipient.RecipientID)) == null)
                {
                    continue;
                }

                var content = recipient.GetContentStream(key);

                content.ContentStream.CopyTo(decryptedData, 4096);
                return;
            }

            throw new CmsException("A suitable private key could not be found for decrypting.");
        }
Ejemplo n.º 4
0
        /// <summary>
        ///   Decrypt CMS protected data.
        /// </summary>
        /// <param name="cipherText">
        ///   The protected CMS data.
        /// </param>
        /// <param name="cancel">
        ///   Is used to stop the task.  When cancelled, the <see cref="TaskCanceledException"/> is raised.
        /// </param>
        /// <returns>
        ///   A task that represents the asynchronous operation. The task's result is
        ///   the plain text byte array of the protected data.
        /// </returns>
        /// <exception cref="KeyNotFoundException">
        ///   When the required private key, to decrypt the data, is not foumd.
        /// </exception>
        /// <remarks>
        ///   Cryptographic Message Syntax (CMS), aka PKCS #7 and
        ///   <see href="https://tools.ietf.org/html/rfc5652">RFC 5652</see>,
        ///   describes an encapsulation syntax for data protection. It
        ///   is used to digitally sign, digest, authenticate, and/or encrypt
        ///   arbitrary message content.
        /// </remarks>
        public async Task <byte[]> ReadProtectedDataAsync(
            byte[] cipherText,
            CancellationToken cancel = default(CancellationToken))
        {
            var cms = new CmsEnvelopedDataParser(cipherText);

            // Find a recipient whose key we hold. We only deal with recipient names
            // issued by ipfs (O=ipfs, OU=keystore).
            var knownKeys = (await ListAsync(cancel).ConfigureAwait(false)).ToArray();
            var recipient = cms
                            .GetRecipientInfos()
                            .GetRecipients()
                            .OfType <RecipientInformation>()
                            .Select(ri =>
            {
                var kid = GetKeyId(ri);
                var key = knownKeys.FirstOrDefault(k => k.Id == kid);
                return(new { recipient = ri, key = key });
            })
                            .FirstOrDefault(r => r.key != null);

            if (recipient == null)
            {
                throw new KeyNotFoundException("The required decryption key is missing.");
            }

            // Decrypt the contents.
            var decryptionKey = await GetPrivateKeyAsync(recipient.key.Name).ConfigureAwait(false);

            return(recipient.recipient.GetContent(decryptionKey));
        }
Ejemplo n.º 5
0
        private void VerifyEnvelopedData(CmsEnvelopedDataParser envelopedParser, string symAlgorithmOID)
        {
            byte[] privKeyData = GetRfc4134Data("BobPrivRSAEncrypt.pri");
            IAsymmetricKeyParameter privKey = PrivateKeyFactory.CreateKey(privKeyData);

            Assert.IsTrue(privKey.IsPrivate);
            Assert.IsTrue(privKey is RsaKeyParameters);

            RecipientInformationStore recipients = envelopedParser.GetRecipientInfos();

            Assert.AreEqual(envelopedParser.EncryptionAlgOid, symAlgorithmOID);

            ArrayList c = new ArrayList(recipients.GetRecipients());

            Assert.LessOrEqual(1, c.Count);
            Assert.GreaterOrEqual(2, c.Count);

            VerifyRecipient((RecipientInformation)c[0], privKey);

            if (c.Count == 2)
            {
                RecipientInformation recInfo = (RecipientInformation)c[1];

                Assert.AreEqual(PkcsObjectIdentifiers.IdAlgCmsRC2Wrap.Id, recInfo.KeyEncryptionAlgOid);
            }
        }
Ejemplo n.º 6
0
        public void TestOriginatorInfo()
        {
            CmsEnvelopedDataParser env = new CmsEnvelopedDataParser(CmsSampleMessages.originatorMessage);

            env.GetRecipientInfos();

            Assert.AreEqual(CmsEnvelopedDataGenerator.DesEde3Cbc, env.EncryptionAlgOid);
        }
Ejemplo n.º 7
0
        public void Test5_2()
        {
            byte[]           data          = GetRfc4134Data("5.2.bin");
            CmsEnvelopedData envelopedData = new CmsEnvelopedData(data);

            VerifyEnvelopedData(envelopedData, CmsEnvelopedDataGenerator.RC2Cbc);

            CmsEnvelopedDataParser envelopedParser = new CmsEnvelopedDataParser(data);

            VerifyEnvelopedData(envelopedParser, CmsEnvelopedDataGenerator.RC2Cbc);
        }
Ejemplo n.º 8
0
        public void TestWorkingData()
        {
            byte[] keyData = Base64.Decode(
                "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAKrAz/SQKrcQ" +
                "nj9IxHIfKDbuXsMqUpI06s2gps6fp7RDNvtUDDMOciWGFhD45YSy8GO0mPx3" +
                "Nkc7vKBqX4TLcqLUz7kXGOHGOwiPZoNF+9jBMPNROe/B0My0PkWg9tuq+nxN" +
                "64oD47+JvDwrpNOS5wsYavXeAW8Anv9ZzHLU7KwZAgMBAAECgYA/fqdVt+5K" +
                "WKGfwr1Z+oAHvSf7xtchiw/tGtosZ24DOCNP3fcTXUHQ9kVqVkNyzt9ZFCT3" +
                "bJUAdBQ2SpfuV4DusVeQZVzcROKeA09nPkxBpTefWbSDQGhb+eZq9L8JDRSW" +
                "HyYqs+MBoUpLw7GKtZiJkZyY6CsYkAnQ+uYVWq/TIQJBAP5zafO4HUV/w4KD" +
                "VJi+ua+GYF1Sg1t/dYL1kXO9GP1p75YAmtm6LdnOCas7wj70/G1YlPGkOP0V" +
                "GFzeG5KAmAUCQQCryvKU9nwWA+kypcQT9Yr1P4vGS0APYoBThnZq7jEPc5Cm" +
                "ZI82yseSxSeea0+8KQbZ5mvh1p3qImDLEH/iNSQFAkAghS+tboKPN10NeSt+" +
                "uiGRRWNbiggv0YJ7Uldcq3ZeLQPp7/naiekCRUsHD4Qr97OrZf7jQ1HlRqTu" +
                "eZScjMLhAkBNUMZCQnhwFAyEzdPkQ7LpU1MdyEopYmRssuxijZao5JLqQAGw" +
                "YCzXokGFa7hz72b09F4DQurJL/WuDlvvu4jdAkEAxwT9lylvfSfEQw4/qQgZ" +
                "MFB26gqB6Gqs1pHIZCzdliKx5BO3VDeUGfXMI8yOkbXoWbYx5xPid/+N8R//" +
                "+sxLBw==");

            byte[] envData = Base64.Decode(
                "MIAGCSqGSIb3DQEHA6CAMIACAQAxgcQwgcECAQAwKjAlMRYwFAYDVQQKEw1C" +
                "b3VuY3kgQ2FzdGxlMQswCQYDVQQGEwJBVQIBHjANBgkqhkiG9w0BAQEFAASB" +
                "gDmnaDZ0vDJNlaUSYyEXsgbaUH+itNTjCOgv77QTX2ImXj+kTctM19PQF2I1" +
                "0/NL0fjakvCgBTHKmk13a7jqB6cX3bysenHNrglHsgNGgeXQ7ggAq5fV/JQQ" +
                "T7rSxEtuwpbuHQnoVUZahOHVKy/a0uLr9iIh1A3y+yZTZaG505ZJMIAGCSqG" +
                "SIb3DQEHATAdBglghkgBZQMEAQIEENmkYNbDXiZxJWtq82qIRZKggAQgkOGr" +
                "1JcTsADStez1eY4+rO4DtyBIyUYQ3pilnbirfPkAAAAAAAAAAAAA");


            CmsEnvelopedDataParser ep = new CmsEnvelopedDataParser(envData);

            RecipientInformationStore recipients = ep.GetRecipientInfos();

            Assert.AreEqual(ep.EncryptionAlgOid, CmsEnvelopedDataGenerator.Aes128Cbc);

            ICollection c = recipients.GetRecipients();

//            PKCS8EncodedKeySpec	keySpec = new PKCS8EncodedKeySpec(keyData);
//            KeyFactory			keyFact = KeyFactory.GetInstance("RSA");
//            Key					priKey = keyFact.generatePrivate(keySpec);
            AsymmetricKeyParameter priKey = PrivateKeyFactory.CreateKey(keyData);

            byte[] data = Hex.Decode("57616c6c6157616c6c6157617368696e67746f6e");

            foreach (RecipientInformation recipient in c)
            {
                Assert.AreEqual(recipient.KeyEncryptionAlgOid, PkcsObjectIdentifiers.RsaEncryption.Id);

                CmsTypedStream recData = recipient.GetContentStream(priKey);

                byte[] compare = CmsTestUtil.StreamToByteArray(recData.ContentStream);
                Assert.IsTrue(Arrays.AreEqual(data, compare));
            }
        }
        public static byte[] DekrypterData2(byte[] kryptertData, AsymmetricKeyParameter privateKey)
        {
            CmsEnvelopedDataParser    cmsEnvelopedDataParser    = new CmsEnvelopedDataParser(kryptertData);
            RecipientInformationStore recipientInformationStore = cmsEnvelopedDataParser.GetRecipientInfos();

            IEnumerator enumerator = recipientInformationStore.GetRecipients().GetEnumerator();

            enumerator.MoveNext();
            RecipientInformation recipientInformation = enumerator.Current as RecipientInformation;

            return(recipientInformation.GetContent(privateKey));
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Decrypt the specified encryptedData.
        /// </summary>
        /// <returns>The decrypted <see cref="MimeKit.MimeEntity"/>.</returns>
        /// <param name="encryptedData">The encrypted data.</param>
        /// <param name="signatures">A list of digital signatures if the data was both signed and encrypted.</param>
        /// <exception cref="System.ArgumentNullException">
        /// <paramref name="encryptedData"/> is <c>null</c>.
        /// </exception>
        public override MimeEntity Decrypt(Stream encryptedData, out IList <IDigitalSignature> signatures)
        {
            // FIXME: find out what exceptions BouncyCastle can throw...
            if (encryptedData == null)
            {
                throw new ArgumentNullException("encryptedData");
            }

            var enveloped  = new CmsEnvelopedDataParser(encryptedData);
            var recipients = enveloped.GetRecipientInfos();
            var algorithm  = enveloped.EncryptionAlgorithmID;
            AsymmetricKeyParameter key;

            foreach (RecipientInformation recipient in recipients.GetRecipients())
            {
                if ((key = GetPrivateKey(recipient.RecipientID)) == null)
                {
                    continue;
                }

                var content = recipient.GetContent(key);

                try {
                    var parser = new CmsSignedDataParser(content);
                    var signed = parser.GetSignedContent();

                    using (var memory = new MemoryStream()) {
                        signed.ContentStream.CopyTo(memory, 4096);
                        content = memory.ToArray();
                    }

                    signatures = GetDigitalSignatures(parser);
                } catch (Exception ex) {
                    Console.WriteLine("Failed to verify signed data: {0}", ex);
                    signatures = null;
                }

                using (var memory = new MemoryStream(content, false)) {
                    var parser = new MimeParser(memory, MimeFormat.Entity);
                    return(parser.ParseEntity());
                }
            }

            throw new CmsException("Can't decrypt.");
        }
Ejemplo n.º 11
0
        public void TestTwoAesKek()
        {
            byte[]       data = Encoding.ASCII.GetBytes("WallaWallaWashington");
            KeyParameter kek1 = CmsTestUtil.MakeAes192Key();
            KeyParameter kek2 = CmsTestUtil.MakeAes192Key();

            CmsEnvelopedDataStreamGenerator edGen = new CmsEnvelopedDataStreamGenerator();

            byte[] kekId1 = new byte[] { 1, 2, 3, 4, 5 };
            byte[] kekId2 = new byte[] { 5, 4, 3, 2, 1 };

            edGen.AddKekRecipient("AES192", kek1, kekId1);
            edGen.AddKekRecipient("AES192", kek2, kekId2);

            MemoryStream bOut = new MemoryStream();

            Stream outStream = edGen.Open(
                bOut,
                CmsEnvelopedDataGenerator.DesEde3Cbc);

            outStream.Write(data, 0, data.Length);

            outStream.Close();

            CmsEnvelopedDataParser ep = new CmsEnvelopedDataParser(bOut.ToArray());

            RecipientInformationStore recipients = ep.GetRecipientInfos();

            Assert.AreEqual(ep.EncryptionAlgOid, CmsEnvelopedDataGenerator.DesEde3Cbc);

            RecipientID recSel = new RecipientID();

            recSel.KeyIdentifier = kekId2;

            RecipientInformation recipient = recipients.GetFirstRecipient(recSel);

            Assert.AreEqual(recipient.KeyEncryptionAlgOid, "2.16.840.1.101.3.4.1.25");

            CmsTypedStream recData = recipient.GetContentStream(kek2);

            Assert.IsTrue(Arrays.AreEqual(data, CmsTestUtil.StreamToByteArray(recData.ContentStream)));

            ep.Close();
        }
Ejemplo n.º 12
0
        public void TestECKeyAgree()
        {
            byte[] data = Hex.Decode("504b492d4320434d5320456e76656c6f706564446174612053616d706c65");

            CmsEnvelopedDataStreamGenerator edGen = new CmsEnvelopedDataStreamGenerator();

            edGen.AddKeyAgreementRecipient(
                CmsEnvelopedDataGenerator.ECDHSha1Kdf,
                OrigECKP.Private,
                OrigECKP.Public,
                ReciECCert,
                CmsEnvelopedDataGenerator.Aes128Wrap);

            MemoryStream bOut = new MemoryStream();

            Stream outStr = edGen.Open(bOut, CmsEnvelopedDataGenerator.Aes128Cbc);

            outStr.Write(data, 0, data.Length);

            outStr.Close();

            CmsEnvelopedDataParser ep = new CmsEnvelopedDataParser(bOut.ToArray());

            RecipientInformationStore recipients = ep.GetRecipientInfos();

            Assert.AreEqual(ep.EncryptionAlgOid, CmsEnvelopedDataGenerator.Aes128Cbc);

            RecipientID recSel = new RecipientID();

//			recSel.SetIssuer(PrincipalUtilities.GetIssuerX509Principal(ReciECCert).GetEncoded());
            recSel.Issuer       = PrincipalUtilities.GetIssuerX509Principal(ReciECCert);
            recSel.SerialNumber = ReciECCert.SerialNumber;

            RecipientInformation recipient = recipients.GetFirstRecipient(recSel);

            CmsTypedStream recData = recipient.GetContentStream(ReciECKP.Private);

            Assert.IsTrue(Arrays.AreEqual(data, CmsTestUtil.StreamToByteArray(recData.ContentStream)));

            ep.Close();
        }
        public void decode(Stream stream)
        {
            CmsEnvelopedDataParser cmsEnvelopedDataParser = new CmsEnvelopedDataParser(b);
            RecipientID            recipientID            = new RecipientID();

            recipientID.SerialNumber = c.Certificate.SerialNumber;
            recipientID.Issuer       = c.Certificate.IssuerDN;
            CmsTypedStream contentStream = cmsEnvelopedDataParser.GetRecipientInfos().GetFirstRecipient(recipientID).GetContentStream(d.Key);

            byte[]         buffer          = new byte[8192];
            BufferedStream bufferedStream  = new BufferedStream(contentStream.ContentStream, 8192);
            BufferedStream bufferedStream2 = new BufferedStream(stream, 8192);
            int            count;

            while ((count = bufferedStream.Read(buffer, 0, 8192)) > 0)
            {
                bufferedStream2.Write(buffer, 0, count);
            }
            bufferedStream2.Flush();
            bufferedStream.Close();
        }
Ejemplo n.º 14
0
        public void TestAesKek()
        {
            byte[]       data = Encoding.ASCII.GetBytes("WallaWallaWashington");
            KeyParameter kek  = CmsTestUtil.MakeAes192Key();

            CmsEnvelopedDataStreamGenerator edGen = new CmsEnvelopedDataStreamGenerator();

            byte[] kekId = new byte[] { 1, 2, 3, 4, 5 };

            edGen.AddKekRecipient("AES192", kek, kekId);

            MemoryStream bOut = new MemoryStream();

            Stream outStream = edGen.Open(
                bOut,
                CmsEnvelopedDataGenerator.DesEde3Cbc);

            outStream.Write(data, 0, data.Length);

            outStream.Close();

            CmsEnvelopedDataParser ep = new CmsEnvelopedDataParser(bOut.ToArray());

            RecipientInformationStore recipients = ep.GetRecipientInfos();

            Assert.AreEqual(ep.EncryptionAlgOid, CmsEnvelopedDataGenerator.DesEde3Cbc);

            ICollection c = recipients.GetRecipients();

            foreach (RecipientInformation recipient in c)
            {
                Assert.AreEqual(recipient.KeyEncryptionAlgOid, "2.16.840.1.101.3.4.1.25");

                CmsTypedStream recData = recipient.GetContentStream(kek);

                Assert.IsTrue(Arrays.AreEqual(data, CmsTestUtil.StreamToByteArray(recData.ContentStream)));
            }

            ep.Close();
        }
Ejemplo n.º 15
0
        private void VerifyData(
            byte[]  encodedBytes,
            string expectedOid,
            byte[]  expectedData)
        {
            CmsEnvelopedDataParser    ep         = new CmsEnvelopedDataParser(encodedBytes);
            RecipientInformationStore recipients = ep.GetRecipientInfos();

            Assert.AreEqual(ep.EncryptionAlgOid, expectedOid);

            ICollection c = recipients.GetRecipients();

            foreach (RecipientInformation recipient in c)
            {
                Assert.AreEqual(recipient.KeyEncryptionAlgOid, PkcsObjectIdentifiers.RsaEncryption.Id);

                CmsTypedStream recData = recipient.GetContentStream(ReciKP.Private);

                Assert.IsTrue(Arrays.AreEqual(expectedData, CmsTestUtil.StreamToByteArray(
                                                  recData.ContentStream)));
            }
        }
Ejemplo n.º 16
0
        public void TestKeyTransAes128()
        {
            byte[] data = Encoding.ASCII.GetBytes("WallaWallaWashington");

            CmsEnvelopedDataStreamGenerator edGen = new CmsEnvelopedDataStreamGenerator();

            edGen.AddKeyTransRecipient(ReciCert);

            MemoryStream bOut = new MemoryStream();

            Stream outStream = edGen.Open(
                bOut, CmsEnvelopedDataGenerator.Aes128Cbc);

            outStream.Write(data, 0, data.Length);

            outStream.Close();

            CmsEnvelopedDataParser ep = new CmsEnvelopedDataParser(bOut.ToArray());

            RecipientInformationStore recipients = ep.GetRecipientInfos();

            Assert.AreEqual(ep.EncryptionAlgOid, CmsEnvelopedDataGenerator.Aes128Cbc);

            ICollection c = recipients.GetRecipients();

            foreach (RecipientInformation recipient in c)
            {
                Assert.AreEqual(recipient.KeyEncryptionAlgOid, PkcsObjectIdentifiers.RsaEncryption.Id);

                CmsTypedStream recData = recipient.GetContentStream(ReciKP.Private);

                Assert.IsTrue(Arrays.AreEqual(data, CmsTestUtil.StreamToByteArray(recData.ContentStream)));
            }

            ep.Close();
        }
Ejemplo n.º 17
0
		private void VerifyEnvelopedData(CmsEnvelopedDataParser envelopedParser, string symAlgorithmOID)
		{
			byte[] privKeyData = GetRfc4134Data("BobPrivRSAEncrypt.pri");
			AsymmetricKeyParameter privKey = PrivateKeyFactory.CreateKey(privKeyData);
			Assert.IsTrue(privKey.IsPrivate);
			Assert.IsTrue(privKey is RsaKeyParameters);

			RecipientInformationStore recipients = envelopedParser.GetRecipientInfos();

			Assert.AreEqual(envelopedParser.EncryptionAlgOid, symAlgorithmOID);

			ArrayList c = new ArrayList(recipients.GetRecipients());
			Assert.LessOrEqual(1, c.Count);
			Assert.GreaterOrEqual(2, c.Count);

			VerifyRecipient((RecipientInformation)c[0], privKey);

			if (c.Count == 2)
			{
				RecipientInformation recInfo = (RecipientInformation)c[1];

				Assert.AreEqual(PkcsObjectIdentifiers.IdAlgCmsRC2Wrap.Id, recInfo.KeyEncryptionAlgOid);
			}
		}
Ejemplo n.º 18
0
		public void Test5_2()
		{
			byte[] data = GetRfc4134Data("5.2.bin");
			CmsEnvelopedData envelopedData = new CmsEnvelopedData(data);

			VerifyEnvelopedData(envelopedData, CmsEnvelopedDataGenerator.RC2Cbc);

			CmsEnvelopedDataParser envelopedParser = new CmsEnvelopedDataParser(data);

			VerifyEnvelopedData(envelopedParser, CmsEnvelopedDataGenerator.RC2Cbc);
		}
Ejemplo n.º 19
0
        public void TestKeyTransAes128Throughput()
        {
            byte[] data = new byte[40001];
            for (int i = 0; i != data.Length; i++)
            {
                data[i] = (byte)(i & 0xff);
            }

            //
            // buffered
            //
            CmsEnvelopedDataStreamGenerator edGen = new CmsEnvelopedDataStreamGenerator();

            edGen.SetBufferSize(BufferSize);

            edGen.AddKeyTransRecipient(ReciCert);

            MemoryStream bOut = new MemoryStream();

            Stream outStream = edGen.Open(bOut, CmsEnvelopedDataGenerator.Aes128Cbc);

            for (int i = 0; i != data.Length; i++)
            {
                outStream.WriteByte(data[i]);
            }

            outStream.Close();

            CmsEnvelopedDataParser    ep         = new CmsEnvelopedDataParser(bOut.ToArray());
            RecipientInformationStore recipients = ep.GetRecipientInfos();
            ICollection c = recipients.GetRecipients();

            IEnumerator e = c.GetEnumerator();

            if (e.MoveNext())
            {
                RecipientInformation recipient = (RecipientInformation)e.Current;

                Assert.AreEqual(recipient.KeyEncryptionAlgOid, PkcsObjectIdentifiers.RsaEncryption.Id);

                CmsTypedStream recData = recipient.GetContentStream(ReciKP.Private);

                Stream       dataStream = recData.ContentStream;
                MemoryStream dataOut    = new MemoryStream();
                int          len;
                byte[]       buf   = new byte[BufferSize];
                int          count = 0;

                while (count != 10 && (len = dataStream.Read(buf, 0, buf.Length)) > 0)
                {
                    Assert.AreEqual(buf.Length, len);

                    dataOut.Write(buf, 0, buf.Length);
                    count++;
                }

                len = dataStream.Read(buf, 0, buf.Length);
                dataOut.Write(buf, 0, len);

                Assert.IsTrue(Arrays.AreEqual(data, dataOut.ToArray()));
            }
            else
            {
                Assert.Fail("recipient not found.");
            }
        }