示例#1
0
        public void TestTwoAesKek()
        {
            byte[]       data = Encoding.Default.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();
        }
示例#2
0
    public static Stream ReplaceSigners(Stream original, SignerInformationStore signerInformationStore, Stream outStr)
    {
        CmsSignedDataStreamGenerator cmsSignedDataStreamGenerator = new CmsSignedDataStreamGenerator();
        CmsSignedDataParser          cmsSignedDataParser          = new CmsSignedDataParser(original);

        cmsSignedDataStreamGenerator.AddSigners(signerInformationStore);
        CmsTypedStream signedContent = cmsSignedDataParser.GetSignedContent();
        bool           flag          = signedContent != null;
        Stream         stream        = cmsSignedDataStreamGenerator.Open(outStr, cmsSignedDataParser.SignedContentType.Id, flag);

        if (flag)
        {
            Streams.PipeAll(signedContent.ContentStream, stream);
        }
        cmsSignedDataStreamGenerator.AddAttributeCertificates(cmsSignedDataParser.GetAttributeCertificates("Collection"));
        cmsSignedDataStreamGenerator.AddCertificates(cmsSignedDataParser.GetCertificates("Collection"));
        cmsSignedDataStreamGenerator.AddCrls(cmsSignedDataParser.GetCrls("Collection"));
        Platform.Dispose(stream);
        return(outStr);
    }
示例#3
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();
        }
示例#5
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();
        }
        public certificate Validate(byte[] data, byte[] signature)
        {
            using (var dataStream = new MemoryStream(data))
                using (var signatureStream = new MemoryStream(signature))
                {
                    var cmsTypedStream      = new CmsTypedStream(dataStream);
                    var cmsSignedDataParser = new CmsSignedDataParser(cmsTypedStream, signatureStream);

                    var store       = cmsSignedDataParser.GetCertificates("Collection");
                    var signerInfos = cmsSignedDataParser.GetSignerInfos();
                    var signerInfo  = signerInfos.GetSigners().OfType <SignerInformation>().First();
                    var certificate = store?.GetMatches(signerInfo?.SignerID)
                                      .OfType <X509Certificate>().FirstOrDefault();

                    if (certificate == null)
                    {
                        return(null);
                    }

                    Logger.Debug(
                        CultureInfo.CurrentCulture,
                        "Certificate found in signature {dn}",
                        certificate.SubjectDN.ToString());
                    var now = DateTime.Now;
                    if (now < certificate.NotBefore || now > certificate.NotAfter)
                    {
                        Logger.Info(
                            CultureInfo.CurrentCulture,
                            "The certificate is not valid right now as it is only valid between {startTime}-{endTime}",
                            certificate.NotBefore,
                            certificate.NotAfter);
                    }

                    return(new certificate
                    {
                        subject = certificate.SubjectDN.ToString(),
                        certificate1 = certificate.GetEncoded()
                    });
                }
        }
示例#7
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)));
            }
        }
        private void VerifySignatures(CmsSignedDataParser sp)
        {
            CmsTypedStream sc = sp.GetSignedContent();

            if (sc != null)
            {
                sc.Drain();
            }

            IX509Store             x509Certs = sp.GetCertificates("Collection");
            SignerInformationStore signers   = sp.GetSignerInfos();

            foreach (SignerInformation signer in signers.GetSigners())
            {
                ICollection certCollection = x509Certs.GetMatches(signer.SignerID);

                IEnumerator certEnum = certCollection.GetEnumerator();
                certEnum.MoveNext();
                X509Certificate cert = (X509Certificate)certEnum.Current;

                VerifySigner(signer, cert);
            }
        }
示例#9
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();
        }
示例#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.");
            }
        }
示例#11
0
 public CmsSignedDataParser(CmsTypedStream signedContent, byte[] sigBlock)
     : this(signedContent, new MemoryStream(sigBlock, writable : false))
 {
 }
示例#12
0
        public MimeEntity DecryptEntity(byte[] encryptedBytes, X509Certificate2 decryptingCertificate)
        {
            try
            {
                if (decryptingCertificate == null)
                {
                    throw new EncryptionException(EncryptionError.NoCertificates);
                }

                // TODO: introduce buffering if you are using large files
                // CMSEnvelopeData is a PKCS# structure  rfc4134
                var envelopedData = new CmsEnvelopedData(encryptedBytes);
                var envData       = EnvelopedData.GetInstance(envelopedData.ContentInfo.Content);

                using (var session = GetSession())
                {
                    if (session == null)
                    {
                        return(null);
                    }

                    foreach (Asn1Sequence asn1Set in envData.RecipientInfos)
                    {
                        var recip = RecipientInfo.GetInstance(asn1Set);
                        var keyTransRecipientInfo = KeyTransRecipientInfo.GetInstance(recip.Info);

                        var sessionKey = Pkcs11Util.Decrypt(session, keyTransRecipientInfo, decryptingCertificate);

#if DEBUG
                        Console.WriteLine(Asn1Dump.DumpAsString(envData));
#endif
                        if (sessionKey == null)
                        {
                            continue;
                        }

                        var recipientId           = new RecipientID();
                        var issuerAndSerialNumber = (IssuerAndSerialNumber)keyTransRecipientInfo.RecipientIdentifier.ID;
                        recipientId.Issuer       = issuerAndSerialNumber.Name;
                        recipientId.SerialNumber = issuerAndSerialNumber.SerialNumber.Value;
                        var recipientInformation = envelopedData.GetRecipientInfos().GetRecipients(recipientId);
                        var recipients           = new ArrayList(recipientInformation);

                        //
                        // read the encrypted content info
                        //
                        var encInfo      = envData.EncryptedContentInfo;
                        var encAlg       = encInfo.ContentEncryptionAlgorithm;
                        var readable     = new CmsProcessableByteArray(encInfo.EncryptedContent.GetOctets());
                        var keyParameter = ParameterUtilities.CreateKeyParameter(encAlg.Algorithm.Id, sessionKey);

                        // Todo: does this work with multi recipient?
                        foreach (RecipientInformation recipient in recipients)
                        {
                            var cmsReadable    = GetReadable(keyParameter, encAlg, readable);
                            var cmsTypedStream = new CmsTypedStream(cmsReadable.GetInputStream());
                            var contentBytes   = StreamToByteArray(cmsTypedStream.ContentStream);
                            var mimeEntity     = MimeSerializer.Default.Deserialize <MimeEntity>(contentBytes);
                            return(mimeEntity);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Error.NotifyEvent(this, ex);
            }

            return(null);
        }