Esempio n. 1
0
        /*
         * /// <exception cref="System.IO.IOException"></exception>
         * public override Document ExtendDocument(Document document, Document originalDocument
         *  , SignatureParameters parameters)
         * {
         *  CAdESSignatureExtension extension = GetExtensionProfile(parameters);
         *  if (extension != null)
         *  {
         *      return extension.ExtendSignatures(document, originalDocument, parameters);
         *  }
         *  else
         *  {
         *      //LOG.Info("No extension for " + parameters.SignatureFormat);
         *  }
         *  return document;
         * }
         */

        private CmsSignedDataGenerator CreateCMSSignedDataGenerator(ISignatureFactory factory,
                                                                    SignatureParameters parameters, CAdESProfileBES cadesProfile,
                                                                    bool includeUnsignedAttributes, CmsSignedData originalSignedData
                                                                    )
        {
            var signedAttrGen = new DefaultSignedAttributeTableGenerator(
                new AttributeTable(cadesProfile.GetSignedAttributes(parameters)));

            SimpleAttributeTableGenerator unsignedAttrGen = null;

            if (includeUnsignedAttributes)
            {
                var attributes = cadesProfile.GetUnsignedAttributes(parameters);
                if (attributes.Count != 0)
                {
                    unsignedAttrGen = new SimpleAttributeTableGenerator(new AttributeTable(attributes));
                }
            }

            SignerInfoGeneratorBuilder sigInfoGeneratorBuilder = new SignerInfoGeneratorBuilder();

            sigInfoGeneratorBuilder.WithSignedAttributeGenerator(signedAttrGen);
            if (unsignedAttrGen != null)
            {
                sigInfoGeneratorBuilder.WithUnsignedAttributeGenerator(unsignedAttrGen);
            }

            CmsSignedDataGenerator generator = new CmsSignedDataGenerator();

            generator.AddSignerInfoGenerator(sigInfoGeneratorBuilder.Build(factory, parameters.SigningCertificate));

            if (originalSignedData != null)
            {
                generator.AddSigners(originalSignedData.GetSignerInfos());
            }

            var certs = new List <X509Certificate>();

            certs.Add(parameters.SigningCertificate);
            if (parameters.CertificateChain != null)
            {
                foreach (X509Certificate cert in parameters.CertificateChain)
                {
                    if (!cert.SubjectDN.Equals(parameters.SigningCertificate.SubjectDN))
                    {
                        certs.Add(cert);
                    }
                }
            }
            IX509Store certStore = X509StoreFactory.Create("Certificate/Collection",
                                                           new X509CollectionStoreParameters(certs));

            generator.AddCertificates(certStore);
            if (originalSignedData != null)
            {
                generator.AddCertificates(originalSignedData.GetCertificates("Collection"));
            }

            return(generator);
        }
Esempio n. 2
0
        public byte[] GetSignature(byte[] content)
        {
            var cer = _Provider.GetCertificate();

            if (cer == null)
            {
                throw new InvalidOperationException("Certificate not found.");
            }

            var cert          = DotNetUtilities.FromX509Certificate(cer);
            var signaturePair = DotNetUtilities.GetKeyPair(cer.PrivateKey);

            IList certList = new ArrayList();
            IList crlList  = new ArrayList();

            certList.Add(cert);

            IX509Store x509Certs = X509StoreFactory.Create("Certificate/Collection", new X509CollectionStoreParameters(certList));
            IX509Store x509Crls  = X509StoreFactory.Create("CRL/Collection", new X509CollectionStoreParameters(crlList));

            var gen = new CmsSignedDataGenerator();

            gen.AddCertificates(x509Certs);

            gen.AddSigner(signaturePair.Private, cert, CmsSignedGenerator.DigestSha256);
            //gen.AddCrls(x509Crls);

            var cmsSignedData = gen.Generate(new CmsProcessableByteArray(content), false);
            var signature     = cmsSignedData.GetEncoded(Asn1Encodable.Der);

            return(signature);
        }
Esempio n. 3
0
        static void SignManifest(ZipFile zipFile, byte[] manifestFileData, X509Certificate2 signingCertificate, X509Certificate2Collection chainCertificates)
        {
            var signingCert = DotNetUtilities.FromX509Certificate(signingCertificate);

            var certList = new System.Collections.ArrayList();

            foreach (X509Certificate2 cert in chainCertificates)
            {
                certList.Add(DotNetUtilities.FromX509Certificate(cert));
            }

            var privateKey = DotNetUtilities.GetKeyPair(signingCertificate.PrivateKey).Private;
            var generator  = new CmsSignedDataGenerator();

            generator.AddSigner(privateKey, signingCert, CmsSignedDataGenerator.DigestSha1);

            Org.BouncyCastle.X509.Store.X509CollectionStoreParameters PP = new Org.BouncyCastle.X509.Store.X509CollectionStoreParameters(certList);
            Org.BouncyCastle.X509.Store.IX509Store st1 = Org.BouncyCastle.X509.Store.X509StoreFactory.Create("CERTIFICATE/COLLECTION", PP);

            generator.AddCertificates(st1);

            var content    = new CmsProcessableByteArray(manifestFileData);
            var signedData = generator.Generate(content, false);

            var data = signedData.GetEncoded();

            zipFile.AddEntry("signature", data);
        }
Esempio n. 4
0
        static void SignManifest(ZipFile zipFile, byte[] manifestFileData, X509Certificate2 certificate)
        {
            var cert = DotNetUtilities.FromX509Certificate(certificate);

            var privateKey = DotNetUtilities.GetKeyPair(certificate.PrivateKey).Private;
            var generator  = new CmsSignedDataGenerator();

            generator.AddSigner(privateKey, cert, CmsSignedDataGenerator.DigestSha1);

            var certList = new System.Collections.ArrayList();

            //var a1Cert = new X509Certificate2(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "AppleWWDRCA.cer"));
            //var a2Cert = new X509Certificate2(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "AppleIncRootCertificate.cer"));

            certList.Add(cert);
            //certList.Add(DotNetUtilities.FromX509Certificate(a1Cert));
            //certList.Add(DotNetUtilities.FromX509Certificate(a2Cert));

            Org.BouncyCastle.X509.Store.X509CollectionStoreParameters PP = new Org.BouncyCastle.X509.Store.X509CollectionStoreParameters(certList);
            Org.BouncyCastle.X509.Store.IX509Store st1 = Org.BouncyCastle.X509.Store.X509StoreFactory.Create("CERTIFICATE/COLLECTION", PP);

            generator.AddCertificates(st1);

            var content    = new CmsProcessableByteArray(manifestFileData);
            var signedData = generator.Generate(content, false);

            var data = signedData.GetEncoded();

            zipFile.AddEntry("signature", data);
        }
Esempio n. 5
0
        private static string SignEnvelop(string signCert, string password, string envelopCert, string orgData)
        {
            var pkcs12StoreBuilder = new Pkcs12StoreBuilder();
            var pkcs12Store        = pkcs12StoreBuilder.Build();

            pkcs12Store.Load(new MemoryStream(Convert.FromBase64String(signCert)), password.ToCharArray());

            var aliases    = pkcs12Store.Aliases;
            var enumerator = aliases.GetEnumerator();

            enumerator.MoveNext();
            var alias   = enumerator.Current.ToString();
            var privKey = pkcs12Store.GetKey(alias);

            var x509Cert   = pkcs12Store.GetCertificate(alias).Certificate;
            var sha1Signer = SignerUtilities.GetSigner("SHA1withRSA");

            sha1Signer.Init(true, privKey.Key);

            var gen = new CmsSignedDataGenerator();

            gen.AddSignerInfoGenerator(new SignerInfoGeneratorBuilder().Build(new Asn1SignatureFactory("SHA1withRSA", privKey.Key), x509Cert));
            gen.AddCertificates(X509StoreFactory.Create("Certificate/Collection", new X509CollectionStoreParameters(new ArrayList {
                x509Cert
            })));

            var sigData  = gen.Generate(new CmsProcessableByteArray(Encoding.UTF8.GetBytes(orgData)), true);
            var signData = sigData.GetEncoded();

            var certificate = DotNetUtilities.FromX509Certificate(new X509Certificate2(Convert.FromBase64String(envelopCert)));
            var rst         = Convert.ToBase64String(EncryptEnvelop(certificate, signData));

            return(rst);
        }
Esempio n. 6
0
        private string SignMessage(string msg, bool isProd)
        {
            var gen = new CmsSignedDataGenerator();
            X509Certificate2 certificate = GetCertificate(isProd);
            var privKey = DotNetUtilities.GetRsaKeyPair(certificate.GetRSAPrivateKey()).Private;
            var cert    = DotNetUtilities.FromX509Certificate(certificate);

            gen.AddSigner(privKey, cert, CmsSignedDataGenerator.DigestSha1);
            var certX509 = DotNetUtilities.ToX509Certificate(cert.CertificateStructure);
            var certList = new List <Org.BouncyCastle.X509.X509Certificate>();

            certList.Add(cert);
            X509CollectionStoreParameters PP = new X509CollectionStoreParameters(certList);
            IX509Store st1 = X509StoreFactory.Create("CERTIFICATE/COLLECTION", PP);

            gen.AddCertificates(st1);
            Encoding EncodedMsg = Encoding.UTF8;

            byte[]         dataToSign = EncodedMsg.GetBytes(msg);
            CmsProcessable data       = new CmsProcessableByteArray(dataToSign);
            CmsSignedData  signed     = gen.Generate(PkcsObjectIdentifiers.Pkcs7, data, true);
            var            result     = signed.GetEncoded();

            return(Convert.ToBase64String(result));
        }
Esempio n. 7
0
        protected byte[] GenerateSignature(byte[] manifest, X509Certificate2 appleCert, X509Certificate2 passCert)
        {
            X509Certificate apple = DotNetUtilities.FromX509Certificate(appleCert);
            X509Certificate cert  = DotNetUtilities.FromX509Certificate(passCert);

            var privateKey = DotNetUtilities.GetKeyPair(passCert.PrivateKey).Private;
            var generator  = new CmsSignedDataGenerator();

            generator.AddSigner(privateKey, cert, CmsSignedGenerator.DigestSha1);

            var list = new List <X509Certificate>();

            list.Add(cert);
            list.Add(apple);

            X509CollectionStoreParameters storeParameters = new X509CollectionStoreParameters(list);
            IX509Store store509 = X509StoreFactory.Create("CERTIFICATE/COLLECTION", storeParameters);

            generator.AddCertificates(store509);

            var content   = new CmsProcessableByteArray(manifest);
            var signature = generator.Generate(content, false).GetEncoded();

            return(signature);
        }
Esempio n. 8
0
        /// <summary>
        /// Exports the certificates for the specified mailboxes.
        /// </summary>
        /// <returns>A new <see cref="MimeKit.Cryptography.ApplicationPkcs7Mime"/> instance containing
        /// the exported keys.</returns>
        /// <param name="mailboxes">The mailboxes.</param>
        /// <exception cref="System.ArgumentNullException">
        /// <paramref name="mailboxes"/> is <c>null</c>.
        /// </exception>
        /// <exception cref="System.ArgumentException">
        /// A certificate for one or more of the <paramref name="mailboxes"/> could not be found.
        /// </exception>
        public override MimePart Export(IEnumerable <MailboxAddress> mailboxes)
        {
            // FIXME: find out what exceptions BouncyCastle can throw...
            if (mailboxes == null)
            {
                throw new ArgumentNullException("mailboxes");
            }

            var certificates = new X509CertificateStore();
            int count        = 0;

            foreach (var mailbox in mailboxes)
            {
                var recipient = GetCmsRecipient(mailbox);
                certificates.Add(recipient.Certificate);
                count++;
            }

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

            var cms = new CmsSignedDataGenerator();

            cms.AddCertificates(certificates);

            var signedData = cms.Generate(new CmsProcessableByteArray(new byte[0]), false);
            var memory     = new MemoryStream(signedData.GetEncoded(), false);

            return(new ApplicationPkcs7Mime(SecureMimeType.CertsOnly, memory));
        }
Esempio n. 9
0
        private void SignManigestFile(PassGeneratorRequest request)
        {
            X509Certificate2 card = GetCertificate(request);

            if (card == null)
            {
                throw new FileNotFoundException("Certificate could not be found. Please ensure the thumbprint and cert location values are correct.");
            }

            Org.BouncyCastle.X509.X509Certificate          cert       = DotNetUtilities.FromX509Certificate(card);
            Org.BouncyCastle.Crypto.AsymmetricKeyParameter privateKey = DotNetUtilities.GetKeyPair(card.PrivateKey).Private;

            X509Certificate2 appleCA = GetAppleCertificate();

            Org.BouncyCastle.X509.X509Certificate appleCert = DotNetUtilities.FromX509Certificate(appleCA);

            ArrayList intermediateCerts = new ArrayList();

            intermediateCerts.Add(appleCert);
            intermediateCerts.Add(cert);

            Org.BouncyCastle.X509.Store.X509CollectionStoreParameters PP = new Org.BouncyCastle.X509.Store.X509CollectionStoreParameters(intermediateCerts);
            Org.BouncyCastle.X509.Store.IX509Store st1 = Org.BouncyCastle.X509.Store.X509StoreFactory.Create("CERTIFICATE/COLLECTION", PP);

            CmsSignedDataGenerator generator = new CmsSignedDataGenerator();

            generator.AddSigner(privateKey, cert, CmsSignedDataGenerator.DigestSha1);
            generator.AddCertificates(st1);

            CmsProcessable content    = new CmsProcessableByteArray(manifestFile);
            CmsSignedData  signedData = generator.Generate(content, false);

            signatureFile = signedData.GetEncoded();
        }
Esempio n. 10
0
        /// <summary>
        /// Create a trust bundle.
        /// </summary>
        public byte[] Create(IResourceProvider bundleResources)
        {
            CmsSignedData s;
            var           validMetadata = ValidMetaData(bundleResources.Metadata);

            IList                  certs     = bundleResources.LoadCertificates();
            IX509Store             x509Certs = X509StoreFactory.Create("Certificate/Collection", new X509CollectionStoreParameters(certs));
            CmsSignedDataGenerator gen       = new CmsSignedDataGenerator();

            gen.AddCertificates(x509Certs);

            if (!string.IsNullOrEmpty(validMetadata))
            {
                byte[]         metadataBytes = Encoding.ASCII.GetBytes(validMetadata);
                CmsProcessable msg           = new CmsProcessableByteArray(metadataBytes);
                s = gen.Generate(CmsSignedGenerator.Data, msg, true);
            }
            else
            {
                s = gen.Generate(CmsSignedGenerator.Data, null, false);
            }

            var p7BData = s.GetEncoded();

            return(p7BData);
        }
Esempio n. 11
0
        public static byte[] GenerateSignature(List <X509Certificate> certificateChain, AsymmetricKeyEntry privateKey, byte[] messageToSign, AttributeTable signedAttributesTable)
        {
            X509Certificate signingCertificate = certificateChain[certificateChain.Count - 1];

#if MAX_CMS_COMPATIBILITY
            // Optional: This is the order that codesign uses:
            List <X509Certificate> cmsChain = new List <X509Certificate>();
            if (certificateChain.Count > 1)
            {
                cmsChain.AddRange(certificateChain.GetRange(0, certificateChain.Count - 1));
                cmsChain.Reverse();
            }
            cmsChain.Add(signingCertificate);
            certificateChain = cmsChain;
#endif
            IX509Store certificateStore = X509StoreFactory.Create("Certificate/Collection", new X509CollectionStoreParameters(certificateChain));

            CmsSignedDataGenerator generator = new CmsSignedDataGenerator();
#if MAX_CMS_COMPATIBILITY
            // Optional: BouncyCastle v1.8.3 has the option to use DER instead of BER to store the certificate chain
            generator.UseDerForCerts = true;
#endif
            generator.AddSigner(privateKey.Key, signingCertificate, CmsSignedDataGenerator.DigestSha256, signedAttributesTable, null);
            generator.AddCertificates(certificateStore);
            CmsSignedData cmsSignature = generator.Generate(CmsSignedGenerator.Data, new CmsProcessableByteArray(messageToSign), false);
            return(cmsSignature.GetEncoded());
        }
Esempio n. 12
0
        public byte[] Sign(byte[] cmsData)
        {
            IList certs = new List <X509Certificate>();

            byte[]           signBytes = File.ReadAllBytes(GetFile());
            X509Certificate2 signCert  = new X509Certificate2(signBytes, Key, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable);

            certs.Add(DotNetUtilities.FromX509Certificate(signCert));
            IX509Store x509Certs = X509StoreFactory.Create("Certificate/Collection", new X509CollectionStoreParameters(certs));

            CmsSignedDataGenerator  gen              = new CmsSignedDataGenerator();
            AsymmetricCipherKeyPair pair             = DotNetUtilities.GetKeyPair(signCert.PrivateKey);
            X509Certificate         bX509Certificate = DotNetUtilities.FromX509Certificate(signCert);

            gen.AddSigner(pair.Private, bX509Certificate, CmsSignedGenerator.DigestSha1);
            gen.AddSigner(pair.Private, bX509Certificate, CmsSignedGenerator.DigestSha256);
            CmsSignedData unsignedData = new CmsSignedData(cmsData);


            gen.AddCertificates(x509Certs);
            CmsProcessable msg           = new CmsProcessableByteArray(unsignedData.GetEncoded());
            CmsSignedData  cmsSignedData = gen.Generate(CmsSignedGenerator.Data, msg, true);

            byte[] p7MData = cmsSignedData.GetEncoded();
            return(p7MData);
        }
Esempio n. 13
0
        private byte[] EncodeAndSign(string input)
        {
            var _signingCertificate         = GetSigningCertificate(string.Empty);
            AsymmetricCipherKeyPair keyPair = DotNetUtilities.GetKeyPair(_signingCertificate.PrivateKey);
            X509Certificate         bouncy  = new X509CertificateParser().ReadCertificate(_signingCertificate.GetRawCertData());

            byte[] content              = new UTF8Encoding().GetBytes(input);
            var    signedDataGenerator  = new CmsSignedDataGenerator();
            var    processableByteArray = new CmsProcessableByteArray(content);

            IList certCollection = new ArrayList();
            var   chain          = new X509Chain();

            chain.Build(_signingCertificate);
            foreach (X509ChainElement link in chain.ChainElements)
            {
                certCollection.Add(DotNetUtilities.FromX509Certificate(link.Certificate));
            }
            IX509Store certStore = X509StoreFactory.Create("Certificate/Collection",
                                                           new X509CollectionStoreParameters(
                                                               certCollection));

            signedDataGenerator.AddCertificates(certStore);
            signedDataGenerator.AddSigner(keyPair.Private, bouncy, CmsSignedGenerator.DigestSha1);

            CmsSignedData signedData = signedDataGenerator.Generate(processableByteArray, true);

            return(signedData.GetEncoded());
        }
Esempio n. 14
0
    protected static byte[] SignWithSystem(byte[] data, AsymmetricKeyParameter key, X509Certificate cert, X509Certificate[] chain)
    {
        var generator = new CmsSignedDataGenerator();

        // Add signing key
        generator.AddSigner(
            key,
            cert,
            "2.16.840.1.101.3.4.2.1"); // SHA256 digest ID
        var storeCerts = new List <X509Certificate>();

        storeCerts.Add(cert);       // NOTE: Adding end certificate too
        storeCerts.AddRange(chain); // I'm assuming the chain collection doesn't contain the end certificate already
        // Construct a store from the collection of certificates and add to generator
        var storeParams = new X509CollectionStoreParameters(storeCerts);
        var certStore   = X509StoreFactory.Create("CERTIFICATE/COLLECTION", storeParams);

        generator.AddCertificates(certStore);

        // Generate the signature
        var signedData = generator.Generate(
            new CmsProcessableByteArray(data),
            false); // encapsulate = false for detached signature

        return(signedData.GetEncoded());
    }
Esempio n. 15
0
        private void SignManigestFile(PassGeneratorRequest request, string manifestFileAndPath)
        {
            byte[] dataToSign = File.ReadAllBytes(manifestFileAndPath);

            X509Certificate2 card = GetCertificate(request);

            Org.BouncyCastle.X509.X509Certificate          cert       = DotNetUtilities.FromX509Certificate(card);
            Org.BouncyCastle.Crypto.AsymmetricKeyParameter privateKey = DotNetUtilities.GetKeyPair(card.PrivateKey).Private;

            X509Certificate2 appleCA = GetAppleCertificate();

            Org.BouncyCastle.X509.X509Certificate appleCert = DotNetUtilities.FromX509Certificate(appleCA);

            ArrayList intermediateCerts = new ArrayList();

            intermediateCerts.Add(appleCert);
            intermediateCerts.Add(cert);

            Org.BouncyCastle.X509.Store.X509CollectionStoreParameters PP = new Org.BouncyCastle.X509.Store.X509CollectionStoreParameters(intermediateCerts);
            Org.BouncyCastle.X509.Store.IX509Store st1 = Org.BouncyCastle.X509.Store.X509StoreFactory.Create("CERTIFICATE/COLLECTION", PP);

            CmsSignedDataGenerator generator = new CmsSignedDataGenerator();

            generator.AddSigner(privateKey, cert, CmsSignedDataGenerator.DigestSha1);
            generator.AddCertificates(st1);

            CmsProcessable content    = new CmsProcessableByteArray(dataToSign);
            CmsSignedData  signedData = generator.Generate(content, false);

            string outputDirectory      = Path.GetDirectoryName(manifestFileAndPath);
            string signatureFileAndPath = Path.Combine(outputDirectory, "signature");

            File.WriteAllBytes(signatureFileAndPath, signedData.GetEncoded());
        }
Esempio n. 16
0
        public static byte[] Sign(byte[] data, string certificatePath, string keyPath, string password)
        {
            var certParser  = new X509CertificateParser();
            var certificate = certParser.ReadCertificate(File.ReadAllBytes(certificatePath));

            AsymmetricKeyParameter asymmetricKey;

            using (var keyReader = new StreamReader(keyPath))
            {
                var pem = new PemReader(keyReader);
                asymmetricKey = (AsymmetricKeyParameter)pem.ReadObject();
            }

            var generator = new CmsSignedDataGenerator();

            generator.AddSigner(
                asymmetricKey,
                certificate,
                CmsSignedGenerator.EncryptionEcgost34102012256,
                CmsSignedGenerator.DigestGost3412012256);

            generator.AddCertificates(
                X509StoreFactory.Create(
                    "Certificate/Collection",
                    new X509CollectionStoreParameters(new[] { certificate })));
            return(generator.Generate(new CmsProcessableByteArray(data), false)
                   .GetEncoded());
        }
Esempio n. 17
0
        byte[] CreateKeyVaultSignature(X509Certificate2 publicCert, SignatureManifest signatureManifest)
        {
            var chain = new X509Chain();

            chain.Build(publicCert);

            // Get the chain as bc certs
            var additionals = chain.ChainElements.Cast <X509ChainElement>()
                              .Select(ce => DotNetUtilities.FromX509Certificate(ce.Certificate))
                              .ToList();

            chain.Dispose();

            var bcCer = DotNetUtilities.FromX509Certificate(publicCert);

            var store = X509StoreFactory.Create("Certificate/Collection", new X509CollectionStoreParameters(additionals));

            var generator = new CmsSignedDataGenerator();
            var builder   = new SignerInfoGeneratorBuilder();

            var b = builder.Build(new RsaSignatureFactory("SHA256WITHRSA", provider), bcCer);

            generator.AddSignerInfoGenerator(b);
            generator.AddCertificates(store);

            var msg  = new CmsProcessableByteArray(signatureManifest.GetBytes());
            var data = generator.Generate(msg, true);

            var encoded = data.GetEncoded();

            return(encoded);
        }
Esempio n. 18
0
        private void SignManigestFile(PassGeneratorRequest request)
        {
            Trace.TraceInformation("Signing the manifest file...");

            X509Certificate2 card = GetCertificate(request);

            if (card == null)
            {
                throw new FileNotFoundException("Certificate could not be found. Please ensure the thumbprint and cert location values are correct.");
            }

            X509Certificate2 appleCA = GetAppleCertificate(request);

            if (appleCA == null)
            {
                throw new FileNotFoundException("Apple Certficate could not be found. Please downloaad from http://www.apple.com/certificateauthority/ and install into your LOCAL MACHINE certificate store.");
            }

            try
            {
                Org.BouncyCastle.X509.X509Certificate          cert       = DotNetUtilities.FromX509Certificate(card);
                Org.BouncyCastle.Crypto.AsymmetricKeyParameter privateKey = DotNetUtilities.GetKeyPair(card.PrivateKey).Private;

                Trace.TraceInformation("Fetching Apple Certificate for signing..");

                Org.BouncyCastle.X509.X509Certificate appleCert = DotNetUtilities.FromX509Certificate(appleCA);

                Trace.TraceInformation("Constructing the certificate chain..");

                ArrayList intermediateCerts = new ArrayList();

                intermediateCerts.Add(appleCert);
                intermediateCerts.Add(cert);

                Org.BouncyCastle.X509.Store.X509CollectionStoreParameters PP = new Org.BouncyCastle.X509.Store.X509CollectionStoreParameters(intermediateCerts);
                Org.BouncyCastle.X509.Store.IX509Store st1 = Org.BouncyCastle.X509.Store.X509StoreFactory.Create("CERTIFICATE/COLLECTION", PP);

                CmsSignedDataGenerator generator = new CmsSignedDataGenerator();

                generator.AddSigner(privateKey, cert, CmsSignedDataGenerator.DigestSha1);
                generator.AddCertificates(st1);

                Trace.TraceInformation("Processing the signature..");

                CmsProcessable content    = new CmsProcessableByteArray(manifestFile);
                CmsSignedData  signedData = generator.Generate(content, false);

                signatureFile = signedData.GetEncoded();

                Trace.TraceInformation("The file has been successfully signed!");
            }
            catch (Exception exp)
            {
                Trace.TraceError("Failed to sign the manifest file: [{0}]", exp.Message);
                throw new ManifestSigningException("Failed to sign manifest", exp);
            }
        }
Esempio n. 19
0
        PrimarySignature CreateKeyVaultPrimarySignature(SignPackageRequest request, SignatureContent signatureContent, SignatureType signatureType)
        {
            // Get the chain

            var getter = typeof(SignPackageRequest).GetProperty("Chain", BindingFlags.Instance | BindingFlags.NonPublic)
                         .GetGetMethod(true);

            var certs = (IReadOnlyList <X509Certificate2>)getter.Invoke(request, null);


            var attribs = SigningUtility.CreateSignedAttributes(request, certs);

            // Convert .NET crypto attributes to Bouncy Castle
            var attribTable = new AttributeTable(new Asn1EncodableVector(attribs.Cast <CryptographicAttributeObject>()
                                                                         .Select(ToBcAttribute)
                                                                         .ToArray()));
            // SignerInfo generator setup
            var signerInfoGeneratorBuilder = new SignerInfoGeneratorBuilder()
                                             .WithSignedAttributeGenerator(new DefaultSignedAttributeTableGenerator(attribTable));


            // Subject Key Identifier (SKI) is smaller and less prone to accidental matching than issuer and serial
            // number.  However, to ensure cross-platform verification, SKI should only be used if the certificate
            // has the SKI extension attribute.

            // Try to look for the value
            var bcCer = DotNetUtilities.FromX509Certificate(request.Certificate);
            var ext   = bcCer.GetExtensionValue(new DerObjectIdentifier(Oids.SubjectKeyIdentifier));
            SignerInfoGenerator signerInfoGenerator;

            if (ext != null)
            {
                var ski = new SubjectKeyIdentifierStructure(ext);
                signerInfoGenerator = signerInfoGeneratorBuilder.Build(new RsaSignatureFactory(HashAlgorithmToBouncyCastle(request.SignatureHashAlgorithm), provider), ski.GetKeyIdentifier());
            }
            else
            {
                signerInfoGenerator = signerInfoGeneratorBuilder.Build(new RsaSignatureFactory(HashAlgorithmToBouncyCastle(request.SignatureHashAlgorithm), provider), bcCer);
            }


            var generator = new CmsSignedDataGenerator();

            generator.AddSignerInfoGenerator(signerInfoGenerator);

            // Get the chain as bc certs
            generator.AddCertificates(X509StoreFactory.Create("Certificate/Collection",
                                                              new X509CollectionStoreParameters(certs.Select(DotNetUtilities.FromX509Certificate).
                                                                                                ToList())));

            var msg  = new CmsProcessableByteArray(signatureContent.GetBytes());
            var data = generator.Generate(msg, true);

            var encoded = data.ContentInfo.GetDerEncoded();

            return(PrimarySignature.Load(encoded));
        }
Esempio n. 20
0
        private CmsSignedDataGenerator CreateCMSSignedDataGenerator(SignatureParameters parameters, CAdESProfileBES cadesProfile, bool includeUnsignedAttributes = true, CmsSignedData originalSignedData = null, byte[] signature = null)
        {
            CmsSignedDataGenerator generator         = new CmsSignedDataGenerator();
            X509Certificate        signerCertificate = parameters.SigningCertificate;

            CmsAttributeTableGenerator signedAttrGen = new DefaultSignedAttributeTableGenerator(new AttributeTable(cadesProfile.GetSignedAttributes(parameters) as System.Collections.IDictionary));

            CmsAttributeTableGenerator unsignedAttrGen = new SimpleAttributeTableGenerator(includeUnsignedAttributes ? new AttributeTable(cadesProfile.GetUnsignedAttributes(parameters) as System.Collections.IDictionary) : null);

            var builder = new SignerInfoGeneratorBuilder().WithSignedAttributeGenerator(signedAttrGen).WithUnsignedAttributeGenerator(unsignedAttrGen);

            generator.AddSignerInfoGenerator(builder.Build(new ReadySignatureFactory(new PreComputedSigner(signature), parameters.DigestWithEncriptionOID), signerCertificate));

            if (originalSignedData != null)
            {
                generator.AddSigners(originalSignedData.GetSignerInfos());
            }
            var certs = new List <X509Certificate>
            {
                parameters.SigningCertificate
            };

            if (parameters.CertificateChain != null)
            {
                foreach (X509Certificate c in parameters.CertificateChain)
                {
                    if (!c.SubjectDN.Equals(parameters.SigningCertificate.SubjectDN))
                    {
                        certs.Add(c);
                    }
                }
            }
            IX509Store certStore = X509StoreFactory.Create("Certificate/Collection", new X509CollectionStoreParameters(certs));

            generator.AddCertificates(certStore);
            if (originalSignedData != null)
            {
                generator.AddCertificates(originalSignedData.GetCertificates("Collection"));
            }
            return(generator);
        }
Esempio n. 21
0
        public void SignedCmsRoundTripWithBouncyCastleLocalCertificate()
        {
            var content = "This is some content";

            // Get cert

            var netcert = GetLocalSignerCert();

            var chain = new X509Chain();

            chain.Build(netcert);

            // Get the chain without the root CA
            var additionals = chain.ChainElements.Cast <X509ChainElement>()
                              .Where(ce => ce.Certificate.Issuer != ce.Certificate.SubjectName.Name)
                              .Select(ce => DotNetUtilities.FromX509Certificate(ce.Certificate))
                              .ToList();

            chain.Dispose();


            var bcCer = DotNetUtilities.FromX509Certificate(netcert);
            var bcKey = DotNetUtilities.GetRsaKeyPair(netcert.GetRSAPrivateKey());

            var store = X509StoreFactory.Create("Certificate/Collection", new X509CollectionStoreParameters(additionals));

            var generator = new CmsSignedDataGenerator();
            var builder   = new SignerInfoGeneratorBuilder();
            var b         = builder.Build(new Asn1SignatureFactory("SHA256WITHRSA", bcKey.Private), bcCer);

            generator.AddSignerInfoGenerator(b);

            //      generator.AddSigner(bcKey.Private, bcCer, CmsSignedDataGenerator.DigestSha256);
            generator.AddCertificates(store);

            var msg  = new CmsProcessableByteArray(Encoding.UTF8.GetBytes(content));
            var data = generator.Generate(msg, true);


            var encoded = data.GetEncoded();


            var signedCms = new SignedCms();

            signedCms.Decode(encoded);
            signedCms.CheckSignature(true); // don't validate the certiciate itself here

            var cContent = signedCms.ContentInfo.Content;
            var str      = Encoding.UTF8.GetString(cContent);

            Assert.Equal(content, str);
        }
Esempio n. 22
0
        public void AssinarCriptografar(EnvioRemessaCobrancaBradescoJson model)
        {
            try
            {
                var utilClass = new MetodosUteis();
                var encoding  = new UTF8Encoding();
                var generator = new CmsSignedDataGenerator();
                var signerInfoGeneratorBuilder = new SignerInfoGeneratorBuilder();
                var certList = new ArrayList();

                var criticas = utilClass.Criticas(model);
                if (criticas.Any())
                {
                    return;
                }

                var data = utilClass.ConverterParaJsonAspasSimples(model);

                var privateCert = this.RetornaCertificado();

                //convertendo certificado para objeto que o bouncycastle conhece
                var bouncyCastleKey      = DotNetUtilities.GetKeyPair(privateCert.PrivateKey).Private;
                var x5091                = new X509Certificate(privateCert.RawData);
                var x509CertBouncyCastle = DotNetUtilities.FromX509Certificate(x5091);

                generator.AddSignerInfoGenerator(signerInfoGeneratorBuilder.Build(new Asn1SignatureFactory("SHA256WithRSA", bouncyCastleKey), x509CertBouncyCastle));

                //criando certstore que o bouncycastle conhece
                certList.Add(x509CertBouncyCastle);

                var store509BouncyCastle = X509StoreFactory.Create("Certificate/Collection", new X509CollectionStoreParameters(certList));
                generator.AddCertificates(store509BouncyCastle);

                var messageBytes = encoding.GetBytes(data);
                var cmsdata      = new CmsProcessableByteArray(messageBytes);

                //assina
                var signeddata    = generator.Generate(cmsdata, true);
                var mensagemFinal = signeddata.GetEncoded();

                //converte para base64 que eh o formato que o serviço espera
                var mensagemConvertidaparaBase64 = Convert.ToBase64String(mensagemFinal);

                //chama serviço convertendo a string na base64 em bytes
                EnviaParaWebService(ParametrosUteis.RetornaUrlEnvio(), encoding.GetBytes(mensagemConvertidaparaBase64));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Esempio n. 23
0
        public async void SignedCmsRoundTripWithKeyVault()
        {
            using (var materialized = await KeyVaultConfigurationDiscoverer.Materialize(certificateConfiguration))
            {
                var content = "This is some content";

                var publicCert = materialized.PublicCertificate;

                // Get cert

                var chain = new X509Chain();
                chain.Build(publicCert);

                // Get the chain without the root CA
                var additionals = chain.ChainElements.Cast <X509ChainElement>()
                                  .Where(ce => ce.Certificate.Issuer != ce.Certificate.SubjectName.Name)
                                  .Select(ce => DotNetUtilities.FromX509Certificate(ce.Certificate))
                                  .ToList();

                chain.Dispose();


                var bcCer = DotNetUtilities.FromX509Certificate(publicCert);

                var store = X509StoreFactory.Create("Certificate/Collection", new X509CollectionStoreParameters(additionals));

                var generator = new CmsSignedDataGenerator();
                var builder   = new SignerInfoGeneratorBuilder();
                var b         = builder.Build(new RsaSignatureFactory("SHA256WITHRSA", materialized.ToRSA()), bcCer);
                generator.AddSignerInfoGenerator(b);
                generator.AddCertificates(store);

                var msg  = new CmsProcessableByteArray(Encoding.UTF8.GetBytes(content));
                var data = generator.Generate(msg, true);


                var encoded = data.GetEncoded();


                var signedCms = new SignedCms();
                signedCms.Decode(encoded);
                signedCms.CheckSignature(true); // don't validate the certiciate itself here

                var cContent = signedCms.ContentInfo.Content;
                var str      = Encoding.UTF8.GetString(cContent);

                Assert.Equal(content, str);
            }
        }
Esempio n. 24
0
        public SignatureFileContainer CreateCadesSignatureFile(ManifestContainer manifestContainer)
        {
            var signedDataGenerator = new CmsSignedDataGenerator();

            signedDataGenerator.AddSigner(
                this.certificateHolder.GetPrivateKey(),
                this.certificateHolder.GetPublicCertificate(),
                CmsSignedDataGenerator.DigestSha256);
            signedDataGenerator.AddSignerInfoGenerator(CreateSignerInfoGenerator());
            signedDataGenerator.AddCertificates(CreateX509Store());
            var signedData =
                signedDataGenerator.Generate(new CmsProcessableByteArray(manifestContainer.Data.ToArray()));

            return(new SignatureFileContainer(manifestContainer.SignatureFileRef, signedData.GetEncoded()));
        }
Esempio n. 25
0
        private static void SavePkcs7Data(X509Certificate bcCertificate, Pkcs10CertificationRequest request, AsymmetricKeyParameter privateKey)
        {
            var requestBytes = request.GetEncoded();

            var typedData = new CmsProcessableByteArray(requestBytes);
            var gen       = new CmsSignedDataGenerator();
            var signerInfoGeneratorBuilder = new SignerInfoGeneratorBuilder();

            var factory = new Asn1SignatureFactory(SingingAlgorithm, privateKey);

            gen.AddSignerInfoGenerator(signerInfoGeneratorBuilder.Build(factory, bcCertificate));
            gen.AddCertificates(MakeCertStore(bcCertificate));

            var signed      = gen.Generate(typedData, true);
            var signedBytes = signed.GetEncoded();
            var cmsBase64   = Convert.ToBase64String(signedBytes);

            /*
             * you can check cert data here - https://lapo.it/asn1js
             * just copy+paste cmsBase64 string
             */

            var cmsData = new StringBuilder();

            cmsData.Append("-----BEGIN CMS-----");
            cmsData.Append("\\n");

            var certLength = cmsBase64.Length;

            for (var i = 0; i < certLength; i += 64)
            {
                var substr = certLength - i >= 64
                    ? cmsBase64.Substring(i, 64)
                    : cmsBase64.Substring(i);

                cmsData.Append(substr);
                cmsData.Append("\\n");
            }

            cmsData.Append("-----END CMS-----");
            cmsData.Append("\\n");
            var cmsString = cmsData.ToString();  //add to http request in bank for approving you certificate

            //after you will need copy bank certificate what approved you certificate from API

            File.WriteAllText(@"certificate.cms", cmsString);
        }
        private byte[] Authenticode(byte[] bRequest, DateTime signTime)
        {
            string requestString = "";

            for (int i = 0; i < bRequest.Length; i++)
            {
                if (bRequest[i] >= 32)
                {
                    requestString += (char)bRequest[i];
                }
            }
            bRequest = Convert.FromBase64String(requestString);

            Asn1InputStream  asn1InputStream = new Asn1InputStream(bRequest);
            Asn1Sequence     instance        = Asn1Sequence.GetInstance(asn1InputStream.ReadObject());
            Asn1Sequence     instance2       = Asn1Sequence.GetInstance(instance[1]);
            Asn1TaggedObject instance3       = Asn1TaggedObject.GetInstance(instance2[1]);
            Asn1OctetString  instance4       = Asn1OctetString.GetInstance(instance3.GetObject());

            byte[] octets = instance4.GetOctets();
            asn1InputStream.Close();

            Asn1EncodableVector signedAttributes = new Asn1EncodableVector();

            signedAttributes.Add(new Attribute(CmsAttributes.ContentType, new DerSet(new DerObjectIdentifier("1.2.840.113549.1.7.1"))));
            signedAttributes.Add(new Attribute(CmsAttributes.SigningTime, new DerSet(new DerUtcTime(signTime))));
            AttributeTable signedAttributesTable = new AttributeTable(signedAttributes);

            signedAttributesTable.ToAsn1EncodableVector();
            DefaultSignedAttributeTableGenerator signedAttributeGenerator = new DefaultSignedAttributeTableGenerator(signedAttributesTable);
            SignerInfoGeneratorBuilder           signerInfoBuilder        = new SignerInfoGeneratorBuilder();

            signerInfoBuilder.WithSignedAttributeGenerator(signedAttributeGenerator);
            ISignatureFactory signatureFactory = new Asn1SignatureFactory(hashAlg + "WithRSA", priKey);


            CmsSignedDataGenerator generator = new CmsSignedDataGenerator();

            generator.AddSignerInfoGenerator(signerInfoBuilder.Build(signatureFactory, x509Cert));
            generator.AddCertificates(x509Store);
            CmsSignedData cmsSignedData = generator.Generate(new CmsProcessableByteArray(octets), true);

            byte[] result = cmsSignedData.ContentInfo.GetEncoded("DER");
            return(Encoding.ASCII.GetBytes(Convert.ToBase64String(result).ToArray()));
        }
Esempio n. 27
0
        public string Signer(string message)
        {
            if (_certificate == null)
            {
                throw new Exception("Certificado não localizado.");
            }
            if (_certificate.PrivateKey == null)
            {
                throw new Exception("chave privada não localizada no certificado.");
            }

            //convertendo certificado para objeto que o bouncycastle conhece
            var bouncyCastleKey      = DotNetUtilities.GetKeyPair(_certificate.PrivateKey).Private;
            var x5091                = new X509Certificate(_certificate.RawData);
            var x509CertBouncyCastle = DotNetUtilities.FromX509Certificate(x5091);

            var generator = new CmsSignedDataGenerator();
            var signerInfoGeneratorBuilder = new SignerInfoGeneratorBuilder();

            generator.AddSignerInfoGenerator(
                signerInfoGeneratorBuilder.Build(new Asn1SignatureFactory("SHA256WithRSA", bouncyCastleKey),
                                                 x509CertBouncyCastle));

            //criando certstore que o bouncycastle conhece
            IList certList = new ArrayList();

            certList.Add(x509CertBouncyCastle);
            var store509BouncyCastle = X509StoreFactory.Create("Certificate/Collection", new X509CollectionStoreParameters(certList));

            generator.AddCertificates(store509BouncyCastle);

            var encoding     = new UTF8Encoding();
            var messageBytes = encoding.GetBytes(message);

            var cmsdata = new CmsProcessableByteArray(messageBytes);

            //assina
            var signeddata   = generator.Generate(cmsdata, true);
            var finalMessage = signeddata.GetEncoded();

            //converte para base64 que eh o formato que o serviço espera
            return(Convert.ToBase64String(finalMessage));
        }
        /// <summary>
        ///  The method used to sign data with private key.
        ///  Signs the provided <code>data</code> and returns both data and
        ///  the signature in a PKCS#7 container.
        ///  https://csharp.hotexamples.com/examples/Org.BouncyCastle.Cms/CmsSignedDataGenerator/AddCrls/php-cmssigneddatagenerator-addcrls-method-examples.html
        /// </summary>
        /// <param name="data"></param>
        /// <param name="signCert"></param>
        /// <returns></returns>
        public static byte[] SignData(byte[] data, X509Certificate2 signCert)
        {
            IList certs = new List <Org.BouncyCastle.X509.X509Certificate>();

            certs.Add(DotNetUtilities.FromX509Certificate(signCert));
            IX509Store              x509Certs = X509StoreFactory.Create("Certificate/Collection", new X509CollectionStoreParameters(certs));
            CmsSignedDataGenerator  gen       = new CmsSignedDataGenerator();
            AsymmetricCipherKeyPair pair      = DotNetUtilities.GetKeyPair(signCert.PrivateKey);

            Org.BouncyCastle.X509.X509Certificate bX509Certificate = DotNetUtilities.FromX509Certificate(signCert);
            gen.AddSigner(pair.Private, bX509Certificate, CmsSignedGenerator.DigestSha256);
            gen.AddCertificates(x509Certs);

            CmsProcessable msg           = new CmsProcessableByteArray(data);
            CmsSignedData  cmsSignedData = gen.Generate(CmsSignedGenerator.Data, msg, true);

            byte[] p7MData = cmsSignedData.GetEncoded();
            return(p7MData);
        }
Esempio n. 29
0
        /// <summary>
        /// Signiert die Daten mit dem angegebenen Absender-Zertifikat
        /// </summary>
        /// <param name="data">Die zu signierenden Daten</param>
        /// <param name="privateKey">Der private Schlüssel mit dem signiert werden soll (passend zum Zeritifikat <paramref name="cert"/>)</param>
        /// <param name="cert">Das Absender-Zertifikat</param>
        /// <param name="certs">Die Zertifikate, die zusätzlich im Ergebnis gespeichert werden sollen (z.B. für eine Zertifkatskette)</param>
        /// <returns>Die signierten Daten</returns>
        public static byte[] SignData(byte[] data, AsymmetricKeyParameter privateKey, X509Certificate cert, IEnumerable <X509Certificate> certs = null)
        {
            var gen      = new CmsSignedDataGenerator();
            var allCerts = new List <X509Certificate>();

            if (certs != null)
            {
                allCerts.AddRange(certs);
            }
            var storeParams = new X509CollectionStoreParameters(allCerts);
            var certStore   = X509StoreFactory.Create("Certificate/Collection", storeParams);

            gen.AddCertificates(certStore);
            gen.AddSigner(privateKey, cert, NistObjectIdentifiers.IdSha256.Id);
            var message    = new CmsProcessableByteArray(data);
            var signedData = gen.Generate(message, true);

            return(signedData.GetEncoded());
        }
        public byte[] Sign(Stream data)
        {
            CmsProcessable msg = new CmsProcessableInputStream(data);

            CmsSignedDataGenerator gen = new CmsSignedDataGenerator();
            SignerInfoGenerator    signerInfoGenerator = new SignerInfoGeneratorBuilder()
                                                         .WithSignedAttributeGenerator(new DefaultSignedAttributeTableGenerator())
                                                         .Build(new Asn1SignatureFactory(algorithm, key), chain[0]);

            gen.AddSignerInfoGenerator(signerInfoGenerator);

            X509CollectionStoreParameters collectionStoreParameters = new X509CollectionStoreParameters(new List <X509Certificate>(chain));
            IX509Store collectionStore = X509StoreFactory.Create("CERTIFICATE/COLLECTION", collectionStoreParameters);

            gen.AddCertificates(collectionStore);

            CmsSignedData sigData = gen.Generate(msg, false);

            return(sigData.GetEncoded());
        }