Exemple #1
0
        public void TestKeyTransOdes()
        {
            byte[] data = Encoding.ASCII.GetBytes("WallaWallaBouncyCastle");

            CmsEnvelopedDataGenerator edGen = new CmsEnvelopedDataGenerator();

            edGen.AddKeyTransRecipient(ReciCert);

            CmsEnvelopedData ed = edGen.Generate(
                new CmsProcessableByteArray(data),
                OiwObjectIdentifiers.DesCbc.Id);

            RecipientInformationStore recipients = ed.GetRecipientInfos();

            Assert.AreEqual(ed.EncryptionAlgOid, OiwObjectIdentifiers.DesCbc.Id);

            ICollection c = recipients.GetRecipients();

            Assert.AreEqual(1, c.Count);

            foreach (RecipientInformation recipient in c)
            {
                byte[] recData = recipient.GetContent(ReciKP.Private);

                Assert.IsTrue(Arrays.AreEqual(data, recData));
            }
        }
        public void TestKeyTransSmallAesUsingAoepMixed()
        {
            byte[] data = new byte[] { 0, 1, 2, 3 };

            CmsEnvelopedDataGenerator edGen = new CmsEnvelopedDataGenerator();

            edGen.AddRecipientInfoGenerator(new KeyTransRecipientInfoGenerator(ReciCert, new Asn1KeyWrapper("RSA/None/OAEPwithSHA256andMGF1withSHA1Padding", ReciCert)));

            CmsEnvelopedData ed = edGen.Generate(
                new CmsProcessableByteArray(data),
                CmsEnvelopedDataGenerator.Aes128Cbc);

            RecipientInformationStore recipients = ed.GetRecipientInfos();

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

            ICollection c = recipients.GetRecipients();

            Assert.AreEqual(1, c.Count);

            foreach (RecipientInformation recipient in c)
            {
                byte[] recData = recipient.GetContent(ReciKP.Private);
                Assert.IsTrue(Arrays.AreEqual(data, recData));
            }
        }
Exemple #3
0
        public void TestKeyTrans128RC4()
        {
            byte[] data = Encoding.ASCII.GetBytes("WallaWallaBouncyCastle");

            CmsEnvelopedDataGenerator edGen = new CmsEnvelopedDataGenerator();

            edGen.AddKeyTransRecipient(ReciCert);

            CmsEnvelopedData ed = edGen.Generate(
                new CmsProcessableByteArray(data),
                "1.2.840.113549.3.4", 128);                  // RC4 OID

            RecipientInformationStore recipients = ed.GetRecipientInfos();

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

            ICollection c = recipients.GetRecipients();

            Assert.AreEqual(1, c.Count);

            foreach (RecipientInformation recipient in c)
            {
                byte[] recData = recipient.GetContent(ReciKP.Private);

                Assert.IsTrue(Arrays.AreEqual(data, recData));
            }
        }
        public void TestKeyTransSmallAesUsingAoepMixedParams()
        {
            byte[] data = new byte[] { 0, 1, 2, 3 };

            CmsEnvelopedDataGenerator edGen = new CmsEnvelopedDataGenerator();

            edGen.AddRecipientInfoGenerator(
                new KeyTransRecipientInfoGenerator(
                    ReciCert,
                    new Asn1KeyWrapper(
                        PkcsObjectIdentifiers.IdRsaesOaep,
                        new RsaesOaepParameters(
                            new AlgorithmIdentifier(NistObjectIdentifiers.IdSha256, DerNull.Instance),
                            new AlgorithmIdentifier(PkcsObjectIdentifiers.IdMgf1, new AlgorithmIdentifier(NistObjectIdentifiers.IdSha224, DerNull.Instance))),
                        ReciCert)));

            CmsEnvelopedData ed = edGen.Generate(
                new CmsProcessableByteArray(data),
                CmsEnvelopedDataGenerator.Aes128Cbc);

            RecipientInformationStore recipients = ed.GetRecipientInfos();

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

            ICollection c = recipients.GetRecipients();

            Assert.AreEqual(1, c.Count);

            foreach (RecipientInformation recipient in c)
            {
                byte[] recData = recipient.GetContent(ReciKP.Private);
                Assert.IsTrue(Arrays.AreEqual(data, recData));
            }
        }
Exemple #5
0
        public void TestECMqvKeyAgreeMultiple()
        {
            byte[] data = Hex.Decode("504b492d4320434d5320456e76656c6f706564446174612053616d706c65");

            CmsEnvelopedDataGenerator edGen = new CmsEnvelopedDataGenerator();

            ArrayList recipientCerts = new ArrayList();

            recipientCerts.Add(ReciECCert);
            recipientCerts.Add(ReciECCert2);

            edGen.AddKeyAgreementRecipients(
                CmsEnvelopedDataGenerator.ECMqvSha1Kdf,
                OrigECKP.Private,
                OrigECKP.Public,
                recipientCerts,
                CmsEnvelopedDataGenerator.Aes128Wrap);

            CmsEnvelopedData ed = edGen.Generate(
                new CmsProcessableByteArray(data),
                CmsEnvelopedDataGenerator.Aes128Cbc);

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

            RecipientInformationStore recipients = ed.GetRecipientInfos();

            ConfirmDataReceived(recipients, data, ReciECCert, ReciECKP.Private);
            ConfirmDataReceived(recipients, data, ReciECCert2, ReciECKP2.Private);
            ConfirmNumberRecipients(recipients, 2);
        }
Exemple #6
0
        private void TryKekAlgorithm(
            KeyParameter kek,
            DerObjectIdentifier algOid)
        {
            byte[] data = Encoding.ASCII.GetBytes("WallaWallaWashington");
            CmsEnvelopedDataGenerator edGen = new CmsEnvelopedDataGenerator();

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

            string keyAlgorithm = ParameterUtilities.GetCanonicalAlgorithmName(algOid.Id);

            edGen.AddKekRecipient(keyAlgorithm, kek, kekId);

            CmsEnvelopedData ed = edGen.Generate(
                new CmsProcessableByteArray(data),
                CmsEnvelopedDataGenerator.DesEde3Cbc);

            RecipientInformationStore recipients = ed.GetRecipientInfos();

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

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

            Assert.IsTrue(c.Count > 0);

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

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

                Assert.IsTrue(Arrays.AreEqual(data, recData));
            }
        }
Exemple #7
0
        private void PasswordUtf8Test(
            string algorithm)
        {
            byte[] data = Hex.Decode("504b492d4320434d5320456e76656c6f706564446174612053616d706c65");

            CmsEnvelopedDataGenerator edGen = new CmsEnvelopedDataGenerator();

            edGen.AddPasswordRecipient(
                new Pkcs5Scheme2Utf8PbeKey("abc\u5639\u563b".ToCharArray(), new byte[20], 5),
                algorithm);

            CmsEnvelopedData ed = edGen.Generate(
                new CmsProcessableByteArray(data),
                CmsEnvelopedDataGenerator.Aes128Cbc);

            RecipientInformationStore recipients = ed.GetRecipientInfos();

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

            ICollection c = recipients.GetRecipients();

            Assert.AreEqual(1, c.Count);

            foreach (PasswordRecipientInformation recipient in c)
            {
                CmsPbeKey key = new Pkcs5Scheme2Utf8PbeKey(
                    "abc\u5639\u563b".ToCharArray(), recipient.KeyDerivationAlgorithm);

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

                Assert.IsTrue(Arrays.AreEqual(data, recData));
            }
        }
        static void Main(string[] args)
        {
            var certificateData = File.ReadAllBytes("YOUR_p7b_FILE");
            var cert            = new X509CertificateParser().ReadCertificate(certificateData);
            //I just wanted to know if I can see the publicKey somehow
            //var publicKey = cert.GetPublicKey();

            var store      = new Pkcs12Store(File.OpenRead("YOUR_p12_File"), "test".ToCharArray());
            var privateKey = store.GetKey("THE_NAME_OF_KEY_YOU_WANT_TO_GET").Key;

            var signedDataGen = new CmsSignedDataGenerator();

            signedDataGen.AddSigner(privateKey, cert, CmsSignedDataGenerator.EncryptionRsa, CmsSignedDataGenerator.DigestSha512);

            var zipContent = new CmsProcessableFile(new FileInfo("YOUR_DATA_FILE"));
            //For me a zip
            var signedData = signedDataGen.Generate(zipContent, true);

            var envDataGen = new CmsEnvelopedDataGenerator();

            envDataGen.AddKeyTransRecipient(cert);

            var sData     = new CmsProcessableByteArray(signedData.GetEncoded());
            var enveloped = envDataGen.Generate(sData, CmsEnvelopedDataGenerator.DesEde3Cbc);

            var dos          = new DerOutputStream(File.OpenWrite("YOUR_DATA_FILE.zip.encrypted.sig)"));
            var bytesToWrite = enveloped.GetEncoded();

            dos.Write(bytesToWrite, 0, bytesToWrite.Length);
            dos.Flush();
            dos.Close();
        }
Exemple #9
0
        private void TryKeyTrans(
            string generatorOID,
            DerObjectIdentifier checkOID,
            Type asn1Params)
        {
            byte[] data = Encoding.ASCII.GetBytes("WallaWallaWashington");

            CmsEnvelopedDataGenerator edGen = new CmsEnvelopedDataGenerator();

            edGen.AddKeyTransRecipient(ReciCert);

            CmsEnvelopedData ed = edGen.Generate(new CmsProcessableByteArray(data), generatorOID);

            RecipientInformationStore recipients = ed.GetRecipientInfos();

            Assert.AreEqual(checkOID.Id, ed.EncryptionAlgOid);

            if (asn1Params != null)
            {
                Assert.IsTrue(asn1Params.IsInstanceOfType(ed.EncryptionAlgorithmID.Parameters));
            }

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

            Assert.AreEqual(1, c.Count);

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

                byte[] recData = recipient.GetContent(ReciKP.Private);

                Assert.IsTrue(Arrays.AreEqual(data, recData));
            }
        }
Exemple #10
0
        public void TestKeyTransSmallAes()
        {
            byte[] data = new byte[] { 0, 1, 2, 3 };

            CmsEnvelopedDataGenerator edGen = new CmsEnvelopedDataGenerator();

            edGen.AddKeyTransRecipient(ReciCert);

            CmsEnvelopedData ed = edGen.Generate(
                new CmsProcessableByteArray(data),
                CmsEnvelopedDataGenerator.Aes128Cbc);

            RecipientInformationStore recipients = ed.GetRecipientInfos();

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

            ICollection c = recipients.GetRecipients();

            Assert.AreEqual(1, c.Count);

            foreach (RecipientInformation recipient in c)
            {
                byte[] recData = recipient.GetContent(ReciKP.Private);
                Assert.IsTrue(Arrays.AreEqual(data, recData));
            }
        }
Exemple #11
0
        private static byte[] EncryptData(byte[] data, X509Certificate encryptionCertificate)
        {
            var dataGenerator = new CmsEnvelopedDataGenerator();

            dataGenerator.AddKeyTransRecipient(encryptionCertificate);
            var encryptedData = dataGenerator.Generate(new CmsProcessableByteArray(data), CmsEnvelopedGenerator.Aes256Cbc);

            return(encryptedData.GetEncoded());
        }
        /// <summary>
        /// The method uses CMS generator to encrypt message using specified algorithm.
        /// https://www.bouncycastle.org/docs/pkixdocs1.5on/org/bouncycastle/cms/CMSEnvelopedDataGenerator.html
        /// </summary>
        /// <param name="message"></param>
        /// <param name="encyptCert"></param>
        /// <returns>CMS Enveloped Data as byte array.</returns>
        public static byte[] CmsEncrypt(byte[] message, X509Certificate2 encyptCert)
        {
            Org.BouncyCastle.X509.X509Certificate cert = DotNetUtilities.FromX509Certificate(encyptCert);
            var envelopGenerator = new CmsEnvelopedDataGenerator();

            envelopGenerator.AddKeyTransRecipient(cert);
            byte[] encodedData = envelopGenerator.Generate(new CmsProcessableByteArray(message), CmsEnvelopedGenerator.DesEde3Cbc).GetEncoded();
            return(encodedData);
        }
Exemple #13
0
        /// <summary>
        /// Verschlüsselt die Daten mit dem angegebenen Empfänger-Zertifikat
        /// </summary>
        /// <param name="data">Die zu verschlüsselnden Daten</param>
        /// <param name="cert">Das Empfänger-Zertifikat</param>
        /// <returns>Die verschlüsselten Daten</returns>
        public static byte[] EncryptData(byte[] data, X509Certificate cert)
        {
            var gen = new CmsEnvelopedDataGenerator();

            gen.AddKeyTransRecipient(cert);
            var message       = new CmsProcessableByteArray(data);
            var envelopedData = gen.Generate(message, PkcsObjectIdentifiers.DesEde3Cbc.Id);
            var encryptedData = envelopedData.GetEncoded();

            return(encryptedData);
        }
        private static byte[] EncryptEnvelop(X509Certificate certificate, byte[] bsOrgData)
        {
            var gen  = new CmsEnvelopedDataGenerator();
            var data = new CmsProcessableByteArray(bsOrgData);

            gen.AddKeyTransRecipient(certificate);

            var enveloped = gen.Generate(data, CmsEnvelopedGenerator.DesEde3Cbc);
            var a         = enveloped.ContentInfo.ToAsn1Object();

            return(a.GetEncoded());
        }
Exemple #15
0
        /// <summary>
        ///   Encrypt data as CMS protected data.
        /// </summary>
        /// <param name="keyName">
        ///   The key name to protect the <paramref name="plainText"/> with.
        /// </param>
        /// <param name="plainText">
        ///   The data to protect.
        /// </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 cipher text of the <paramref name="plainText"/>.
        /// </returns>
        /// <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[]> CreateProtectedDataAsync(
            string keyName,
            byte[] plainText,
            CancellationToken cancel = default(CancellationToken))
        {
            // Identify the recipient by the Subject Key ID.

            // TODO: Need a method to just the get BC public key
            // Get the BC key pair for the named key.
            var ekey = await Store.TryGetAsync(keyName, cancel).ConfigureAwait(false);

            if (ekey == null)
            {
                throw new KeyNotFoundException($"The key '{keyName}' does not exist.");
            }
            AsymmetricCipherKeyPair kp = null;

            UseEncryptedKey(ekey, key =>
            {
                kp = this.GetKeyPairFromPrivateKey(key);
            });

            // Add recipient type based on key type.
            var edGen = new CmsEnvelopedDataGenerator();

            if (kp.Private is RsaPrivateCrtKeyParameters)
            {
                edGen.AddKeyTransRecipient(kp.Public, Base58.Decode(ekey.Id));
            }
            else if (kp.Private is ECPrivateKeyParameters)
            {
                var cert = await CreateBCCertificateAsync(keyName, cancel).ConfigureAwait(false);

                edGen.AddKeyAgreementRecipient(
                    agreementAlgorithm: CmsEnvelopedDataGenerator.ECDHSha1Kdf,
                    senderPrivateKey: kp.Private,
                    senderPublicKey: kp.Public,
                    recipientCert: cert,
                    cekWrapAlgorithm: CmsEnvelopedDataGenerator.Aes256Wrap
                    );
            }
            else
            {
                throw new NotSupportedException($"The key type {kp.Private.GetType().Name} is not supported.");
            }

            // Generate the protected data.
            var ed = edGen.Generate(
                new CmsProcessableByteArray(plainText),
                CmsEnvelopedDataGenerator.Aes256Cbc);

            return(ed.GetEncoded());
        }
Exemple #16
0
        private static byte[] CreateEnvelopedDataPkcs7(byte[] pkcs10RequestData, X509Certificate2Collection caChain)
        {
            if (caChain.Count == 0)
            {
                throw new ArgumentException("The SCEP service did not provide any certificates for SCEP communication");
            }

            // Find a certificate
            // - without key usage extension that forbids Key encipherment
            var CertsWithoutKeyUsageExtensionMissingKeyEncipherment = caChain.OfType <X509Certificate2>()
                                                                      .Select(cert => new Tuple <X509Certificate2, IEnumerable <X509Extension> >(cert, cert.Extensions.OfType <X509Extension>()))
                                                                      .Where(tuple => !tuple.Item2.OfType <X509KeyUsageExtension>().Any(ku => !ku.KeyUsages.HasFlag(X509KeyUsageFlags.KeyEncipherment))); // certificates with Key Usage Extension but without Key Encipherment are not possible

            if (!CertsWithoutKeyUsageExtensionMissingKeyEncipherment.Any())
            {
                throw new ArgumentException("The SCEP service provided its certificate, but it is not suitable for SCEP (KeyEncipherment as Key Usage");
            }

            // - that is trusted (trusted root anchor and unrevoked)
            var UsableCerts = CertsWithoutKeyUsageExtensionMissingKeyEncipherment
                              .Where(tuple => tuple.Item1.Verify());

            if (!UsableCerts.Any())
            {
                throw new ArgumentException("The SCEP service uses a certificate that is not trusted in this context. Add the CA certificate to the Trusted Root store in Windows.");
            }

            // if possible, use a CA
            X509Certificate2 scepEncryptionCert = UsableCerts
                                                  .SingleOrDefault(tuple => !tuple.Item2.OfType <X509BasicConstraintsExtension>().Any(bc => bc.CertificateAuthority)) // prefer CAs
                                                  ?.Item1;

            if (null == scepEncryptionCert)
            {
                scepEncryptionCert = UsableCerts.First().Item1; // if there is no good CA, we will take the first cert with key encipherment
            }
            //if (null == scepEncryptionCert)
            //    scepEncryptionCert = caChain[0];

            X509CertificateParser x509Parser     = new X509CertificateParser();
            X509Certificate       certEncryption = x509Parser.ReadCertificate(scepEncryptionCert.Export(X509ContentType.Cert));

            CmsEnvelopedDataGenerator edGen = new CmsEnvelopedDataGenerator();

            edGen.AddKeyTransRecipient(certEncryption);

            CmsProcessable   deliveredCertContent = new CmsProcessableByteArray(pkcs10RequestData);
            CmsEnvelopedData envelopedDataResult  = edGen.Generate(deliveredCertContent, CmsEnvelopedGenerator.Aes256Cbc);

            return(envelopedDataResult.ContentInfo.GetDerEncoded());
        }
        /// <summary>
        ///Basic constructor - specify the contents of the PKIArchiveControl structure.
        /// </summary>
        /// <param name="privateKeyInfo">the private key to be archived.</param>
        /// <param name="generalName">the general name to be associated with the private key.</param>
        ///
        public PkiArchiveControlBuilder(PrivateKeyInfo privateKeyInfo, GeneralName generalName)
        {
            EncKeyWithID encKeyWithID = new EncKeyWithID(privateKeyInfo, generalName);

            try
            {
                this.keyContent = new CmsProcessableByteArray(CrmfObjectIdentifiers.id_ct_encKeyWithID, encKeyWithID.GetEncoded());
            }
            catch (IOException e)
            {
                throw new InvalidOperationException("unable to encode key and general name info", e);
            }

            this.envGen = new CmsEnvelopedDataGenerator();
        }
        public static byte[] KrypterData(byte[] ukryptertBytes, X509Certificate sertifikat)
        {
/*            AlgorithmIdentifier hash = new AlgorithmIdentifier(NistObjectIdentifiers.IdSha256, DerNull.Instance);
*           AlgorithmIdentifier mask = new AlgorithmIdentifier(PkcsObjectIdentifiers.IdMgf1, hash);
*           AlgorithmIdentifier pSource = new AlgorithmIdentifier(PkcsObjectIdentifiers.IdPSpecified, new DerOctetString(new byte[0]));
*           RsaesOaepParameters parameters = new RsaesOaepParameters(hash, mask, pSource);
*           AlgorithmIdentifier keyEncryptionScheme = new AlgorithmIdentifier(PkcsObjectIdentifiers.IdRsaesOaep, parameters);*/

            CmsEnvelopedDataGenerator envelopedDataGenerator = new CmsEnvelopedDataGenerator();

            envelopedDataGenerator.AddKeyTransRecipient(sertifikat);
            CmsEnvelopedData cmsData = envelopedDataGenerator.Generate(new CmsProcessableByteArray(ukryptertBytes), CmsEnvelopedGenerator.Aes256Cbc);

            return(cmsData.GetEncoded());
        }
Exemple #19
0
        public string Encrypt(string plainText)
        {
            byte[] plainBytes            = Encoding.UTF8.GetBytes(plainText);
            CmsProcessableByteArray cpba = new CmsProcessableByteArray(plainBytes);

            CmsEnvelopedDataGenerator envelopedGen = new CmsEnvelopedDataGenerator();

            foreach (X509Certificate2 cert in publicCerts)
            {
                Org.BouncyCastle.X509.X509Certificate bouncyCert = DotNetUtilities.FromX509Certificate(cert);
                AsymmetricKeyParameter keyParameter = bouncyCert.GetPublicKey();
                envelopedGen.AddKeyTransRecipient(bouncyCert);
            }

            CmsEnvelopedData envelopedData = envelopedGen.Generate(cpba, CmsEnvelopedGenerator.Aes256Cbc);
            string           cipherString  = Convert.ToBase64String(envelopedData.GetEncoded());

            return(cipherString);
        }
        /// <summary>
        /// encrypts the <paramref name="plainText"/>
        /// </summary>
        /// <param name="plainText"></param>
        /// <returns></returns>
        public string Encrypt(string plainText)
        {
            var plainBytes = Encoding.UTF8.GetBytes(plainText);
            var cpba       = new CmsProcessableByteArray(plainBytes);

            var envelopedGen = new CmsEnvelopedDataGenerator();

            foreach (var cert in _publicCerts)
            {
                var bouncyCert = DotNetUtilities.FromX509Certificate(cert);
                bouncyCert.GetPublicKey();
                envelopedGen.AddKeyTransRecipient(bouncyCert);
            }

            var envelopedData = envelopedGen.Generate(cpba, CmsEnvelopedGenerator.Aes256Cbc);
            var cipherString  = Convert.ToBase64String(envelopedData.GetEncoded());

            return(cipherString);
        }
Exemple #21
0
        Stream Envelope(CmsRecipientCollection recipients, Stream content)
        {
            var cms   = new CmsEnvelopedDataGenerator();
            int count = 0;

            foreach (var recipient in recipients)
            {
                cms.AddKeyTransRecipient(recipient.Certificate);
                count++;
            }

            if (count == 0)
            {
                throw new ArgumentException("No recipients specified.", "recipients");
            }

            // FIXME: how to decide which algorithm to use?
            var input         = new CmsProcessableInputStream(content);
            var envelopedData = cms.Generate(input, CmsEnvelopedGenerator.DesEde3Cbc);

            return(new MemoryStream(envelopedData.GetEncoded(), false));
        }