Example #1
0
        public string Decrypt(string cipherText)
        {
            byte[] cipherBytes   = Convert.FromBase64String(cipherText);
            var    envelopedData = new CmsEnvelopedData(cipherBytes);
            RecipientInformationStore recipientsStore = envelopedData.GetRecipientInfos();
            ICollection recipientsCollection          = recipientsStore.GetRecipients();
            IList       recipients = recipientsCollection as IList;

            byte[] plainBytes = new byte[] { };
            int    index      = 0;

            foreach (KeyTransRecipientInformation recipientInfo in recipients)
            {
                // todo: better approach than catching n exceptions.
                RecipientInformation recipient = recipientsStore.GetFirstRecipient(recipientInfo.RecipientID);
                try
                {
                    plainBytes = recipient.GetContent(this.privateKey);
                    break;
                }
                catch (CmsException e) when(index != recipientsStore.Count - 1)
                {
                }
                index++;
            }
            return(Encoding.UTF8.GetString(plainBytes));
        }
Example #2
0
        /// <summary>
        ///   Get the key ID for a recipient.
        /// </summary>
        /// <param name="ri">
        ///   A recepient of the message.
        /// </param>
        /// <returns>
        ///   The key ID of the recepient or <b>null</b> if the recepient info
        ///   is not understood or does not contain an IPFS key id.
        /// </returns>
        /// <remarks>
        ///   The key ID is either the Subject Key Identifier (preferred) or the
        ///   issuer's distinguished name with the form "CN=&lt;kid>,OU=keystore,O=ipfs".
        /// </remarks>
        MultiHash GetKeyId(RecipientInformation ri)
        {
            // Any errors are simply ignored.
            try
            {
                // Subject Key Identifier is the key ID.
                if (ri.RecipientID.SubjectKeyIdentifier is byte[] ski)
                {
                    return(new MultiHash(ski));
                }

                // Issuer is CN=<kid>,OU=keystore,O=ipfs
                var issuer = ri.RecipientID.Issuer;
                if (issuer != null &&
                    issuer.GetValueList(X509Name.OU).Contains("keystore") &&
                    issuer.GetValueList(X509Name.O).Contains("ipfs"))
                {
                    var cn = issuer.GetValueList(X509Name.CN)[0] as string;
                    return(new MultiHash(cn));
                }
            }
            catch (Exception e)
            {
                log.Warn("Failed reading CMS recipient info.", e);
            }

            return(null);
        }
        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);
            }
        }
        private void VerifyRecipient(RecipientInformation recipient, IAsymmetricKeyParameter privKey)
        {
            Assert.IsTrue(privKey.IsPrivate);

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

            byte[] recData = recipient.GetContent(privKey);

            Assert.IsTrue(Arrays.AreEqual(exContent, recData));
        }
        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));
        }
Example #6
0
        private static void ConfirmDataReceived(RecipientInformationStore recipients,
                                                byte[] expectedData, X509Certificate reciCert, AsymmetricKeyParameter reciPrivKey)
        {
            RecipientID rid = new RecipientID();

            rid.Issuer       = PrincipalUtilities.GetIssuerX509Principal(reciCert);
            rid.SerialNumber = reciCert.SerialNumber;

            RecipientInformation recipient = recipients[rid];

            Assert.IsNotNull(recipient);

            byte[] actualData = recipient.GetContent(reciPrivKey);
            Assert.IsTrue(Arrays.AreEqual(expectedData, actualData));
        }
Example #7
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();
        }
Example #8
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();
        }
Example #9
0
        public void TestRfc4134Ex5_2()
        {
            byte[] data = Hex.Decode("5468697320697320736f6d652073616d706c6520636f6e74656e742e");

//			KeyFactory kFact = KeyFactory.GetInstance("RSA");
//			Key key = kFact.generatePrivate(new PKCS8EncodedKeySpec(bobPrivRsaEncrypt));
            AsymmetricKeyParameter key = PrivateKeyFactory.CreateKey(bobPrivRsaEncrypt);

            CmsEnvelopedData ed = new CmsEnvelopedData(rfc4134ex5_2);

            RecipientInformationStore recipients = ed.GetRecipientInfos();

            Assert.AreEqual("1.2.840.113549.3.2", ed.EncryptionAlgOid);

            ICollection c = recipients.GetRecipients();
            IEnumerator e = c.GetEnumerator();

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

                    if (recipient is KeyTransRecipientInformation)
                    {
                        byte[] recData = recipient.GetContent(key);

                        Assert.IsTrue(Arrays.AreEqual(data, recData));
                    }
                }while (e.MoveNext());
            }
            else
            {
                Assert.Fail("no recipient found");
            }
        }
Example #10
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.");
            }
        }
Example #11
0
		private void VerifyRecipient(RecipientInformation recipient, AsymmetricKeyParameter privKey)
		{
			Assert.IsTrue(privKey.IsPrivate);

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

			byte[] recData = recipient.GetContent(privKey);

			Assert.IsTrue(Arrays.AreEqual(exContent, recData));
		}