예제 #1
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);
        }
예제 #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);
        }
예제 #3
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());
        }
예제 #4
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);
        }
예제 #5
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());
    }
예제 #6
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());
        }
예제 #7
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());
        }
예제 #8
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));
        }
예제 #9
0
        private static CryptographicAttributeObjectCollection CreateAttributeCollection(
            X509Certificate2 certificate,
            AsymmetricKeyParameter privateKey,
            Action <Asn1EncodableVector> addAttributes)
        {
            var content    = new CmsProcessableByteArray(new byte[0]);
            var attributes = new Asn1EncodableVector();

            addAttributes(attributes);

            var signedAttributes   = new AttributeTable(attributes);
            var unsignedAttributes = new AttributeTable(DerSet.Empty);

            var generator = new CmsSignedDataGenerator();

            generator.AddSigner(
                privateKey,
                DotNetUtilities.FromX509Certificate(certificate),
                Oids.Sha256,
                signedAttributes,
                unsignedAttributes);

            var bcSignedCms = generator.Generate(content, encapsulate: true);
            var signedCms   = new SignedCms();

            signedCms.Decode(bcSignedCms.GetEncoded());

            return(signedCms.SignerInfos[0].SignedAttributes);
        }
예제 #10
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());
        }
        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();
        }
예제 #12
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);
        }
예제 #13
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);
        }
예제 #14
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();
        }
예제 #15
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);
            }
        }
예제 #16
0
        public void CreateSign()
        {
            byte[] data = File.ReadAllBytes(Path.Combine(_settings.PackagePath, _manifestFilename));

            X509Certificate2 certificate       = new X509Certificate2(_settings.CertificatePath, _settings.CertificatePassword, X509KeyStorageFlags.Exportable);
            X509Certificate2 intermCertificate = new X509Certificate2(_settings.IntermCertificatePath);

            var privKey = SecurityUtils.GetRsaKeyPair(certificate.GetRSAPrivateKey()).Private;
            var cert    = SecurityUtils.FromX509Certificate(certificate);
            var interm  = SecurityUtils.FromX509Certificate(intermCertificate);

            CmsProcessableByteArray content   = new CmsProcessableByteArray(data);
            CmsSignedDataGenerator  generator = new CmsSignedDataGenerator();

            generator.AddSigner(privKey, cert, CmsSignedGenerator.EncryptionRsa, CmsSignedGenerator.DigestSha256);

            CmsSignedData signedContent = generator.Generate(content, false);
            var           si            = signedContent.GetSignerInfos();
            var           signer        = si.GetSigners().Cast <SignerInformation>().First();

            SignerInfo signerInfo = signer.ToSignerInfo();

            Asn1EncodableVector digestAlgorithmsVector = new Asn1EncodableVector();

            digestAlgorithmsVector.Add(new AlgorithmIdentifier(
                                           algorithm: new DerObjectIdentifier(_oidSHA256),
                                           parameters: DerNull.Instance));

            // Construct SignedData.encapContentInfo
            ContentInfo encapContentInfo = new ContentInfo(
                contentType: new DerObjectIdentifier(_oidPKCS7IdData),
                content: null);

            Asn1EncodableVector certificatesVector = new Asn1EncodableVector();

            certificatesVector.Add(X509CertificateStructure.GetInstance(Asn1Object.FromByteArray(cert.GetEncoded())));
            certificatesVector.Add(X509CertificateStructure.GetInstance(Asn1Object.FromByteArray(interm.GetEncoded())));

            // Construct SignedData.signerInfos
            Asn1EncodableVector signerInfosVector = new Asn1EncodableVector();

            signerInfosVector.Add(signerInfo.ToAsn1Object());

            // Construct SignedData
            SignedData signedData = new SignedData(
                digestAlgorithms: new DerSet(digestAlgorithmsVector),
                contentInfo: encapContentInfo,
                certificates: new BerSet(certificatesVector),
                crls: null,
                signerInfos: new DerSet(signerInfosVector));

            ContentInfo contentInfo = new ContentInfo(
                contentType: new DerObjectIdentifier(_oidPKCS7IdSignedData),
                content: signedData);

            File.WriteAllBytes(Path.Combine(_settings.PackagePath, _signatureFilename), contentInfo.GetDerEncoded());
        }
예제 #17
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()));
        }
        private static byte[] SignData(byte[] data, Pkcs12Store signCertificate, DateTime?requestTimestamp = null)
        {
            var    signCertAlias = signCertificate.Aliases.Cast <string>().First(signCertificate.IsKeyEntry);
            var    signCertEntry = signCertificate.GetCertificate(signCertAlias);
            var    signCert      = signCertEntry.Certificate;
            var    signPkEntry   = signCertificate.GetKey(signCertAlias);
            var    signPk        = signPkEntry.Key;
            string digestName;

            if (signCert.SigAlgOid == PkcsObjectIdentifiers.Sha1WithRsaEncryption.Id)
            {
                digestName = "SHA1";
            }
            else if (signCert.SigAlgOid == PkcsObjectIdentifiers.Sha256WithRsaEncryption.Id)
            {
                digestName = "SHA256";
            }
            else
            {
                throw new ExtraException($"Unsupported digest algorithm {signCert.SigAlgName}");
            }

            var digestOid = DigestUtilities.GetObjectIdentifier(digestName).Id;
            var digest    = DigestUtilities.CalculateDigest(digestName, data);

            var signedAttrs = new Dictionary <object, object>()
            {
                { CmsAttributeTableParameter.Digest, digest }
            };

            if (requestTimestamp.HasValue)
            {
                var signTimestamp = new Org.BouncyCastle.Asn1.Cms.Attribute(CmsAttributes.SigningTime, new DerSet(new Time(requestTimestamp.Value.ToUniversalTime())));
                signedAttrs.Add(signTimestamp.AttrType, signTimestamp);
            }

            var signedAttrGen   = new DefaultSignedAttributeTableGenerator();
            var signedAttrTable = signedAttrGen.GetAttributes(signedAttrs);

            var generator = new CmsSignedDataGenerator();

            generator.AddSigner(signPk, signCert, digestOid, new DefaultSignedAttributeTableGenerator(signedAttrTable), null);

            var signedData = generator.Generate(new CmsProcessableByteArray(data), true);

            return(signedData.GetEncoded());
        }
예제 #19
0
        /// <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);
        }
예제 #20
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());
        }
예제 #21
0
        public static byte[] SignCHUIDByRandomKeyPair(IEnumerable <byte> value)
        {
            var keyPair = new RSAKeyPairGeneratorBC(1024).Generate();

            var certificateGenerator = new X509CertificateGeneratorBC();

            certificateGenerator.SetIssuerDN("CN=ONVIF TT, C=US");
            certificateGenerator.SetSubjectDN("CN=ONVIF TT, C=US");
            certificateGenerator.SetNotValidBefore(DateTime.UtcNow.AddYears(-1));
            certificateGenerator.SetNotValidAfter(DateTime.UtcNow.AddYears(1));
            certificateGenerator.SetSerialNumber();
            certificateGenerator.SetSignatureAlgorithm("SHA1WithRSAEncryption");
            certificateGenerator.SetPublicKey(keyPair.PublicKey);

            var generator = new CmsSignedDataGenerator();

            generator.AddSigner(PrivateKeyFactory.CreateKey(keyPair.PrivateKey),
                                certificateGenerator.Generate(keyPair.PrivateKey).GetEncoded(),
                                CmsSignedDataGenerator.DigestSha1);

            return(generator.Generate(new CmsProcessableByteArray(value.ToArray())).GetEncoded());
        }
예제 #22
0
        public byte[] GetSignedCms(Stream rangedStream)
        {
            rangedStream.Position = 0;

            CmsSignedDataGenerator signedDataGenerator = new CmsSignedDataGenerator();

            var cert = DotNetUtilities.FromX509Certificate(Certificate);
            var key  = DotNetUtilities.GetKeyPair(Certificate.PrivateKey);

            IX509Store x509Certs = X509StoreFactory.Create(
                "Certificate/Collection",
                new X509CollectionStoreParameters(new[] { cert }));

            signedDataGenerator.AddSigner(key.Private, cert, CmsSignedDataGenerator.DigestSha1);
            signedDataGenerator.AddCertificates(x509Certs);

            CmsProcessableInputStream msg = new CmsProcessableInputStream(rangedStream);

            CmsSignedData signedData = signedDataGenerator.Generate(msg, false);

            return(signedData.GetEncoded());
        }
예제 #23
0
        /// <summary>
        /// Get a signature block that java will load a JAR with
        /// </summary>
        /// <param name="sfFileData">The data to sign</param>
        /// <returns>The signature block (including certificate) for the data passed in</returns>
        private byte[] SignIt(byte[] sfFileData)
        {
            AsymmetricKeyParameter privateKey = null;

            var cert = LoadCert(_pemData, out privateKey);

            //create things needed to make the CmsSignedDataGenerator work
            var certStore = X509StoreFactory.Create("Certificate/Collection", new X509CollectionStoreParameters(new List <X509Certificate>()
            {
                cert
            }));
            CmsSignedDataGenerator dataGen = new CmsSignedDataGenerator();

            dataGen.AddCertificates(certStore);
            dataGen.AddSigner(privateKey, cert, CmsSignedDataGenerator.EncryptionRsa, CmsSignedDataGenerator.DigestSha256);

            //content is detached- i.e. not included in the signature block itself
            CmsProcessableByteArray detachedContent = new CmsProcessableByteArray(sfFileData);
            var signedContent = dataGen.Generate(detachedContent, false);

            //do lots of stuff to get things in the proper ASN.1 structure for java to parse it properly.  much trial and error.
            var                 signerInfos            = signedContent.GetSignerInfos();
            var                 signer                 = signerInfos.GetSigners().Cast <SignerInformation>().First();
            SignerInfo          signerInfo             = signer.ToSignerInfo();
            Asn1EncodableVector digestAlgorithmsVector = new Asn1EncodableVector();

            digestAlgorithmsVector.Add(new AlgorithmIdentifier(new DerObjectIdentifier("2.16.840.1.101.3.4.2.1"), DerNull.Instance));
            ContentInfo         encapContentInfo = new ContentInfo(new DerObjectIdentifier("1.2.840.113549.1.7.1"), null);
            Asn1EncodableVector asnVector        = new Asn1EncodableVector();

            asnVector.Add(X509CertificateStructure.GetInstance(Asn1Object.FromByteArray(cert.GetEncoded())));
            Asn1EncodableVector signersVector = new Asn1EncodableVector();

            signersVector.Add(signerInfo.ToAsn1Object());
            SignedData  signedData  = new SignedData(new DerSet(digestAlgorithmsVector), encapContentInfo, new BerSet(asnVector), null, new DerSet(signersVector));
            ContentInfo contentInfo = new ContentInfo(new DerObjectIdentifier("1.2.840.113549.1.7.2"), signedData);

            return(contentInfo.GetDerEncoded());
        }
        /// <summary>
        /// Generates the signed cms data.
        /// </summary>
        /// <returns>The signed cms data.</returns>
        /// <param name="signingData">Signing data.</param>
        /// <param name="signerCert">Signer certificate/</param>
        /// <param name="privateKey">Signer private key.</param>
        private static byte[] GenerateSignedCmsData(DerSet signingData, X509Certificate signerCert, AsymmetricKeyParameter privateKey)
        {
            CmsSignedDataGenerator cmsDataGenerator = new CmsSignedDataGenerator();
            IX509Store             x509Certs        = X509StoreFactory.Create(
                "Certificate/Collection",
                new X509CollectionStoreParameters(new X509Certificate[] { signerCert }));

            cmsDataGenerator.AddCertificates(x509Certs);

            Org.BouncyCastle.Asn1.Cms.AttributeTable attTable = new Org.BouncyCastle.Asn1.Cms.AttributeTable(signingData);
            cmsDataGenerator.AddSigner(
                privateKey,
                signerCert,
                SignerUtilities.GetObjectIdentifier(Sha256WithRsa).Id,
                Sha256Oid,
                new SimpleAttributeTableGenerator(attTable),
                null);

            CmsSignedData detachedSignedData = cmsDataGenerator.Generate(null, false);

            return(detachedSignedData.GetEncoded());
        }
예제 #25
0
        public static byte[] SignBC(string text, X509Certificate2 cert)

        {
            Org.BouncyCastle.X509.X509Certificate          cert2 = DotNetUtilities.FromX509Certificate(cert);
            Org.BouncyCastle.Crypto.AsymmetricKeyParameter K     = DotNetUtilities.GetKeyPair(cert.PrivateKey).Private;
            CmsSignedDataGenerator generator = new CmsSignedDataGenerator();

            generator.AddSigner(K, cert2, CmsSignedDataGenerator.EncryptionRsa, CmsSignedDataGenerator.DigestSha256);

            List <Org.BouncyCastle.X509.X509Certificate> certList = new List <Org.BouncyCastle.X509.X509Certificate>();

            certList.Add(cert2);

            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);
            byte[] data = Encoding.UTF8.GetBytes(text);

            CmsSignedData signedData = generator.Generate(new CmsProcessableByteArray(data), true);

            return(signedData.GetEncoded());
        }
예제 #26
0
        private byte[] SignWithCertificate(byte[] bytesToSign)
        {
            var generator = new CmsSignedDataGenerator();

            var privKey     = _gatewayKeyProvider.SigningPrivateKey;
            var certificate = _gatewayKeyProvider.SigningCertificate;

            var certificates = new List <Org.BouncyCastle.X509.X509Certificate>();

            certificates.Add(certificate);

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

            generator.AddSigner(privKey, certificate, CmsSignedGenerator.EncryptionRsa, CmsSignedGenerator.DigestSha256);

            generator.AddCertificates(store);

            var           message    = new CmsProcessableByteArray(bytesToSign);
            CmsSignedData signedData = generator.Generate(message, false);

            return(signedData.GetEncoded());
        }
예제 #27
0
        //------------------------------------------------------------------------------

        public TimeStampToken Generate(
            TimeStampRequest request,
            BigInteger serialNumber,
            DateTime genTime)
        {
            DerObjectIdentifier digestAlgOID = new DerObjectIdentifier(request.MessageImprintAlgOid);

            AlgorithmIdentifier algID          = new AlgorithmIdentifier(digestAlgOID, DerNull.Instance);
            MessageImprint      messageImprint = new MessageImprint(algID, request.GetMessageImprintDigest());

            Accuracy accuracy = null;

            if (accuracySeconds > 0 || accuracyMillis > 0 || accuracyMicros > 0)
            {
                DerInteger seconds = null;
                if (accuracySeconds > 0)
                {
                    seconds = new DerInteger(accuracySeconds);
                }

                DerInteger millis = null;
                if (accuracyMillis > 0)
                {
                    millis = new DerInteger(accuracyMillis);
                }

                DerInteger micros = null;
                if (accuracyMicros > 0)
                {
                    micros = new DerInteger(accuracyMicros);
                }

                accuracy = new Accuracy(seconds, millis, micros);
            }

            DerBoolean derOrdering = null;

            if (ordering)
            {
                derOrdering = DerBoolean.GetInstance(ordering);
            }

            DerInteger nonce = null;

            if (request.Nonce != null)
            {
                nonce = new DerInteger(request.Nonce);
            }

            DerObjectIdentifier tsaPolicy = new DerObjectIdentifier(tsaPolicyOID);

            if (request.ReqPolicy != null)
            {
                tsaPolicy = new DerObjectIdentifier(request.ReqPolicy);
            }

            TstInfo tstInfo = new TstInfo(tsaPolicy, messageImprint,
                                          new DerInteger(serialNumber), new DerGeneralizedTime(genTime), accuracy,
                                          derOrdering, nonce, tsa, request.Extensions);

            try
            {
                CmsSignedDataGenerator signedDataGenerator = new CmsSignedDataGenerator();

                byte[] derEncodedTstInfo = tstInfo.GetDerEncoded();

                if (request.CertReq)
                {
                    signedDataGenerator.AddCertificates(x509Certs);
                }

                signedDataGenerator.AddCrls(x509Crls);
                signedDataGenerator.AddSigner(key, cert, digestOID, signedAttr, unsignedAttr);

                CmsSignedData signedData = signedDataGenerator.Generate(
                    PkcsObjectIdentifiers.IdCTTstInfo.Id,
                    new CmsProcessableByteArray(derEncodedTstInfo),
                    true);

                return(new TimeStampToken(signedData));
            }
            catch (CmsException cmsEx)
            {
                throw new TspException("Error generating time-stamp token", cmsEx);
            }
            catch (IOException e)
            {
                throw new TspException("Exception encoding info", e);
            }
            catch (X509StoreException e)
            {
                throw new TspException("Exception handling CertStore", e);
            }
//			catch (InvalidAlgorithmParameterException e)
//			{
//				throw new TspException("Exception handling CertStore CRLs", e);
//			}
        }
예제 #28
0
        public TimeStampToken Generate(TimeStampRequest request, BigInteger serialNumber, DateTime genTime)
        {
            DerObjectIdentifier objectID       = new DerObjectIdentifier(request.MessageImprintAlgOid);
            AlgorithmIdentifier hashAlgorithm  = new AlgorithmIdentifier(objectID, DerNull.Instance);
            MessageImprint      messageImprint = new MessageImprint(hashAlgorithm, request.GetMessageImprintDigest());
            Accuracy            accuracy       = null;

            if (this.accuracySeconds > 0 || this.accuracyMillis > 0 || this.accuracyMicros > 0)
            {
                DerInteger seconds = null;
                if (this.accuracySeconds > 0)
                {
                    seconds = new DerInteger(this.accuracySeconds);
                }
                DerInteger millis = null;
                if (this.accuracyMillis > 0)
                {
                    millis = new DerInteger(this.accuracyMillis);
                }
                DerInteger micros = null;
                if (this.accuracyMicros > 0)
                {
                    micros = new DerInteger(this.accuracyMicros);
                }
                accuracy = new Accuracy(seconds, millis, micros);
            }
            DerBoolean derBoolean = null;

            if (this.ordering)
            {
                derBoolean = DerBoolean.GetInstance(this.ordering);
            }
            DerInteger nonce = null;

            if (request.Nonce != null)
            {
                nonce = new DerInteger(request.Nonce);
            }
            DerObjectIdentifier tsaPolicyId = new DerObjectIdentifier(this.tsaPolicyOID);

            if (request.ReqPolicy != null)
            {
                tsaPolicyId = new DerObjectIdentifier(request.ReqPolicy);
            }
            TstInfo        tstInfo = new TstInfo(tsaPolicyId, messageImprint, new DerInteger(serialNumber), new DerGeneralizedTime(genTime), accuracy, derBoolean, nonce, this.tsa, request.Extensions);
            TimeStampToken result;

            try
            {
                CmsSignedDataGenerator cmsSignedDataGenerator = new CmsSignedDataGenerator();
                byte[] derEncoded = tstInfo.GetDerEncoded();
                if (request.CertReq)
                {
                    cmsSignedDataGenerator.AddCertificates(this.x509Certs);
                }
                cmsSignedDataGenerator.AddCrls(this.x509Crls);
                cmsSignedDataGenerator.AddSigner(this.key, this.cert, this.digestOID, this.signedAttr, this.unsignedAttr);
                CmsSignedData signedData = cmsSignedDataGenerator.Generate(PkcsObjectIdentifiers.IdCTTstInfo.Id, new CmsProcessableByteArray(derEncoded), true);
                result = new TimeStampToken(signedData);
            }
            catch (CmsException e)
            {
                throw new TspException("Error generating time-stamp token", e);
            }
            catch (IOException e2)
            {
                throw new TspException("Exception encoding info", e2);
            }
            catch (X509StoreException e3)
            {
                throw new TspException("Exception handling CertStore", e3);
            }
            return(result);
        }
        private CmsSignedData GenerateTimestamp(
            TimeStampRequest request,
            BigInteger serialNumber,
            DateTime generalizedTime)
        {
            var messageImprint = new MessageImprint(
                new AlgorithmIdentifier(
                    new DerObjectIdentifier(request.MessageImprintAlgOid)), request.GetMessageImprintDigest());
            DerInteger nonce = request.Nonce == null ? null : new DerInteger(request.Nonce);

            var tstInfo = new TstInfo(
                new DerObjectIdentifier(_options.Policy.Value),
                messageImprint,
                new DerInteger(serialNumber),
                new DerGeneralizedTime(generalizedTime),
                _options.Accuracy,
                DerBoolean.False,
                nonce,
                tsa: null,
                extensions: null);

            var content          = new CmsProcessableByteArray(tstInfo.GetEncoded());
            var signedAttributes = new Asn1EncodableVector();
            var certificateBytes = new Lazy <byte[]>(() => Certificate.GetEncoded());

            if (_options.SigningCertificateUsage.HasFlag(SigningCertificateUsage.V1))
            {
                byte[] hash = _options.SigningCertificateV1Hash ?? DigestUtilities.CalculateDigest("SHA-1", certificateBytes.Value);
                var    signingCertificate = new SigningCertificate(new EssCertID(hash));
                var    attributeValue     = new DerSet(signingCertificate);
                var    attribute          = new BcAttribute(PkcsObjectIdentifiers.IdAASigningCertificate, attributeValue);

                signedAttributes.Add(attribute);
            }

            if (_options.SigningCertificateUsage.HasFlag(SigningCertificateUsage.V2))
            {
                byte[] hash = DigestUtilities.CalculateDigest("SHA-256", certificateBytes.Value);
                var    signingCertificateV2 = new SigningCertificateV2(new EssCertIDv2(hash));
                var    attributeValue       = new DerSet(signingCertificateV2);
                var    attribute            = new BcAttribute(PkcsObjectIdentifiers.IdAASigningCertificateV2, attributeValue);

                signedAttributes.Add(attribute);
            }

            var generator = new CmsSignedDataGenerator();

            if (_options.ReturnSigningCertificate)
            {
                var certificates = X509StoreFactory.Create(
                    "Certificate/Collection",
                    new X509CollectionStoreParameters(new[] { Certificate }));

                generator.AddCertificates(certificates);
            }

            generator.AddSigner(
                _keyPair.Private,
                Certificate,
                _options.SignatureHashAlgorithm.Value,
                new BcAttributeTable(signedAttributes),
                new BcAttributeTable(DerSet.Empty));

            CmsSignedData signedCms = generator.Generate(
                PkcsObjectIdentifiers.IdCTTstInfo.Id,
                content,
                encapsulate: true);

            return(signedCms);
        }
        static void Main(string[] args)
        {
            byte[] entradaArray = File.ReadAllBytes(@"certificado/arquivoTeste.txt");

            AsymmetricKeyParameter chavePrivada;

            X509Certificate certificadoX509 = getCertificadoX509(@"certificado/certificado.p12", "123!@#", out chavePrivada);

            SHA512Managed hashSHA512 = new SHA512Managed();
            SHA256Managed hashSHA256 = new SHA256Managed();

            byte[] certificadoX509Hash = hashSHA256.ComputeHash(certificadoX509.GetEncoded());
            byte[] EntradaHash         = hashSHA512.ComputeHash(entradaArray);

            CmsSignedDataGenerator geradorCms = new CmsSignedDataGenerator();

            //
            //atributos
            //
            Asn1EncodableVector atributosAssinados = new Asn1EncodableVector();

            //1.2.840.113549.1.9.3 -> ContentType
            //1.2.840.113549.1.7.1 -> RSA Security Data Inc
            atributosAssinados.Add(new Org.BouncyCastle.Asn1.Cms.Attribute(CmsAttributes.ContentType, new DerSet(new DerObjectIdentifier("1.2.840.113549.1.7.1"))));

            //1.2.840.113549.1.9.5 -> Signing Time
            atributosAssinados.Add(new Org.BouncyCastle.Asn1.Cms.Attribute(CmsAttributes.SigningTime, new DerSet(new DerUtcTime(DateTime.Now))));

            //1.2.840.113549.1.9.4 -> messageDigest
            atributosAssinados.Add(new Org.BouncyCastle.Asn1.Cms.Attribute(CmsAttributes.MessageDigest, new DerSet(new DerOctetString(EntradaHash))));

            //2.16.840.1.101.3.4.2.3 -> SHA-512
            //2.16.840.1.101.3.4.2.1 -> SHA-256
            //1.2.840.113549.1.9.16.5.1 -> sigPolicyQualifier-spuri
            DerObjectIdentifier identificadorPolicyID = new DerObjectIdentifier("1.2.840.113549.1.9.16.2.15");

            byte[] policyHASH = System.Text.Encoding.ASCII.GetBytes("0F6FA2C6281981716C95C79899039844523B1C61C2C962289CDAC7811FEEE29E");
            List <SigPolicyQualifierInfo> sigPolicyQualifierInfos = new List <SigPolicyQualifierInfo>();

            Org.BouncyCastle.Asn1.X509.AlgorithmIdentifier algoritmoIdentificador = new Org.BouncyCastle.Asn1.X509.AlgorithmIdentifier("2.16.840.1.101.3.4.2.3");
            SigPolicyQualifierInfo bcSigPolicyQualifierInfo = new SigPolicyQualifierInfo(new DerObjectIdentifier("1.2.840.113549.1.9.16.5.1"), new DerIA5String("http://politicas.icpbrasil.gov.br/PA_AD_RB_v2_2.der"));

            sigPolicyQualifierInfos.Add(bcSigPolicyQualifierInfo);
            SignaturePolicyId signaturePolicyId = new SignaturePolicyId(DerObjectIdentifier.GetInstance(new DerObjectIdentifier("2.16.76.1.7.1.6.2.2")), new OtherHashAlgAndValue(algoritmoIdentificador, new DerOctetString(policyHASH)), sigPolicyQualifierInfos);

            atributosAssinados.Add(new Org.BouncyCastle.Asn1.Cms.Attribute(identificadorPolicyID, new DerSet(signaturePolicyId)));

            //1.2.840.113549.1.9.16.2.47 -> id-aa-signingCertificateV2
            Org.BouncyCastle.Asn1.Ess.EssCertIDv2 essCertIDv2;
            essCertIDv2 = new Org.BouncyCastle.Asn1.Ess.EssCertIDv2(certificadoX509Hash);
            atributosAssinados.Add(new Org.BouncyCastle.Asn1.Cms.Attribute(new DerObjectIdentifier("1.2.840.113549.1.9.16.2.47"), new DerSet(essCertIDv2)));

            AttributeTable atributosAssinadosTabela = new AttributeTable(atributosAssinados);

            //geradorCms.AddSigner(chavePrivada, certificadoX509, CmsSignedDataGenerator.DigestSha256, new DefaultSignedAttributeTableGenerator(atributosAssinadosTabela), null);
            geradorCms.AddSigner(chavePrivada, certificadoX509, CmsSignedDataGenerator.DigestSha512, new DefaultSignedAttributeTableGenerator(atributosAssinadosTabela), null);

            List <X509Certificate> certificadoX509Lista = new List <X509Certificate>();

            certificadoX509Lista.Add(certificadoX509);
            //storeCerts.AddRange(chain);

            X509CollectionStoreParameters parametrosArmazem = new X509CollectionStoreParameters(certificadoX509Lista);
            IX509Store armazemCertificado = X509StoreFactory.Create("CERTIFICATE/COLLECTION", parametrosArmazem);

            geradorCms.AddCertificates(armazemCertificado);

            var dadosAssinado = geradorCms.Generate(new CmsProcessableByteArray(entradaArray), true);     // encapsulate = false for detached signature

            Console.WriteLine("Codificado => " + Convert.ToBase64String(dadosAssinado.GetEncoded()));
        }