Exemplo n.º 1
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);
        }
Exemplo n.º 2
0
        public static byte[] GenerateSignature(List <X509Certificate> certificateChain, AsymmetricKeyEntry privateKey, byte[] messageToSign)
        {
            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();
            generator.AddSigner(privateKey.Key, signingCertificate, CmsSignedDataGenerator.DigestSha256);
            generator.AddCertificates(certificateStore);
#if MAX_CMS_COMPATIBILITY
            // Optional: We use a modified version of BouncyCastle that has the option to use DER instead of BER to store the certificate chain
            CmsSignedData cmsSignature = generator.Generate(CmsSignedGenerator.Data, new CmsProcessableByteArray(messageToSign), false, true);
#else
            CmsSignedData cmsSignature = generator.Generate(CmsSignedGenerator.Data, new CmsProcessableByteArray(messageToSign), false);
#endif
            return(cmsSignature.GetEncoded());
        }
Exemplo 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);
        }
Exemplo 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);
        }
Exemplo n.º 5
0
        private string DigitalSign(string location, string id, string password, byte[] data)
        {
            foreach (var certificatePair in GetCertificates(location))
            {
                var certId = GetCertificateId(certificatePair.Key);
                if (certId == id)
                {
                    var rsa = CertificateManager.DecryptPrivateKey(certificatePair.Value, password);
                    if (rsa == null)
                    {
                        return(null);
                    }

                    var privateKey = DotNetUtilities.GetKeyPair(rsa).Private;

                    var signatureFactory    = new Asn1SignatureFactory("SHA1WITHRSA", privateKey);
                    var signerInfoGenerator = new SignerInfoGeneratorBuilder().Build(signatureFactory, DotNetUtilities.FromX509Certificate(certificatePair.Key));

                    var generator = new CmsSignedDataGenerator();
                    generator.AddSignerInfoGenerator(signerInfoGenerator);

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

                    return(Uri.EscapeDataString(Convert.ToBase64String(signedData.GetEncoded())));
                }
            }

            return(null);
        }
Exemplo n.º 6
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));
        }
Exemplo n.º 7
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);
        }
Exemplo n.º 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));
        }
Exemplo n.º 9
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());
        }
Exemplo n.º 10
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);
        }
Exemplo n.º 11
0
        /// <summary><inheritDoc></inheritDoc></summary>
        /// <exception cref="System.IO.IOException"></exception>
        protected override Document SignDocumentInternal(Document document, SignatureParameters parameters,
                                                         DigestSigner signer)
        {
            if (parameters.SignaturePackaging != SignaturePackaging.ENVELOPING &&
                parameters.SignaturePackaging != SignaturePackaging.DETACHED)
            {
                throw new ArgumentException("Unsupported signature packaging " + parameters.SignaturePackaging);
            }

            ExternalDigestSigner   factory   = new ExternalDigestSigner(signer, parameters);
            CmsSignedDataGenerator generator = CreateCMSSignedDataGenerator(
                factory, parameters, GetSigningProfile(parameters), true, null);

            byte[]                  toBeSigned     = Streams.ReadAll(document.OpenStream());
            var                     content        = new CmsProcessableByteArray(toBeSigned);
            CmsSignedData           data           = generator.Generate(content, parameters.SignaturePackaging != SignaturePackaging.DETACHED);
            Document                signedDocument = new CMSSignedDocument(data);
            CAdESSignatureExtension extension      = GetExtensionProfile(parameters);

            if (extension != null)
            {
                signedDocument = extension.ExtendSignatures(
                    new CMSSignedDocument(data), document, parameters);
            }
            return(signedDocument);
        }
Exemplo n.º 12
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);
        }
        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();
        }
Exemplo n.º 14
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);
        }
Exemplo n.º 15
0
        protected void SignDetached(Stream signed, Stream unsigned, X509Certificate2 selectedCert)
        {
            BC::X509.X509Certificate bcSelectedCert = DotNetUtilities.FromX509Certificate(selectedCert);
#if NETFRAMEWORK
            trace.TraceEvent(TraceEventType.Information, 0, "Signing the message in name of {0}", selectedCert.Subject);
#else
            logger.LogInformation("Signing the message in name of {0}", selectedCert.Subject);
#endif

            BC.Crypto.ISignatureFactory sigFactory;
            try
            {
                SignatureAlgorithm signAlgo = EteeActiveConfig.Seal.NativeSignatureAlgorithm;
                BC::Crypto.AsymmetricCipherKeyPair keyPair = DotNetUtilities.GetKeyPair(selectedCert.PrivateKey);
                sigFactory = new Asn1SignatureFactory(signAlgo.Algorithm.FriendlyName, keyPair.Private);
            }
            catch (CryptographicException)
            {
                SignatureAlgorithm signAlgo = EteeActiveConfig.Seal.WindowsSignatureAlgorithm;
                sigFactory = new WinSignatureFactory(signAlgo.Algorithm, signAlgo.DigestAlgorithm, selectedCert.PrivateKey);
            }

            SignerInfoGenerator sigInfoGen = new SignerInfoGeneratorBuilder()
                                             .Build(sigFactory, bcSelectedCert);

            CmsSignedDataGenerator cmsSignedDataGen = new CmsSignedDataGenerator();
            cmsSignedDataGen.AddSignerInfoGenerator(sigInfoGen);

            CmsSignedData detachedSignature = cmsSignedDataGen.Generate(new CmsProcessableProxy(unsigned), false);

            byte[] detachedSignatureBytes = detachedSignature.GetEncoded();
            signed.Write(detachedSignatureBytes, 0, detachedSignatureBytes.Length);
        }
Exemplo n.º 16
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());
    }
Exemplo 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);
        }
Exemplo n.º 18
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();
        }
Exemplo n.º 19
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);
        }
Exemplo n.º 20
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());
        }
Exemplo n.º 21
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());
        }
Exemplo n.º 22
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());
        }
Exemplo n.º 23
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);
            }
        }
Exemplo n.º 24
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));
        }
Exemplo n.º 25
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);
        }
Exemplo n.º 26
0
        /// <summary>Add a signature to the already CMS signed data document.</summary>
        /// <remarks>Add a signature to the already CMS signed data document.</remarks>
        /// <param name="_signedDocument"></param>
        /// <param name="parameters"></param>
        /// <param name="signatureValue"></param>
        /// <returns></returns>
        /// <exception cref="System.IO.IOException">System.IO.IOException</exception>
        public virtual Document AddASignatureToDocument(Document _signedDocument, SignatureParameters
                                                        parameters, byte[] signatureValue)
        {
            if (parameters.SignaturePackaging != SignaturePackaging.ENVELOPING)
            {
                throw new ArgumentException("Unsupported signature packaging " + parameters.SignaturePackaging);
            }
            try
            {
                CmsSignedData originalSignedData = null;
                using (var stream = _signedDocument.OpenStream())
                {
                    originalSignedData = new CmsSignedData(stream);
                }

                //jbonilla - No aplica para C#
                //string jsAlgorithm = parameters.GetSignatureAlgorithm().GetJavaSignatureAlgorithm
                //    (parameters.GetDigestAlgorithm());
                //PreComputedContentSigner cs = new PreComputedContentSigner(jsAlgorithm, signatureValue
                //    );
                PreComputedSigner s = new PreComputedSigner(signatureValue);
                //DigestCalculatorProvider digestCalculatorProvider = new BcDigestCalculatorProvider
                //    ();
                //CMSSignedDataGenerator generator = CreateCMSSignedDataGenerator(cs, digestCalculatorProvider
                //    , parameters, GetSigningProfile(parameters), true, originalSignedData);
                CmsSignedDataGenerator generator = CreateCMSSignedDataGenerator(s, parameters
                                                                                , GetSigningProfile(parameters), true, originalSignedData);

                //if (originalSignedData == null || originalSignedData.SignedContent.GetContent
                //    () == null)
                if (originalSignedData == null || originalSignedData.SignedContent == null)
                {
                    throw new RuntimeException("Cannot retrieve orignal content");
                }
                //byte[] octetString = (byte[])originalSignedData.SignedContent.GetContent();
                //CmsProcessableByteArray content = new CmsProcessableByteArray(octetString);
                CmsProcessable          content        = originalSignedData.SignedContent;
                CmsSignedData           data           = generator.Generate(content, true);
                Document                signedDocument = new CMSSignedDocument(data);
                CAdESSignatureExtension extension      = GetExtensionProfile(parameters);
                if (extension != null)
                {
                    signedDocument = extension.ExtendSignatures(new CMSSignedDocument(data), null, parameters);
                }
                return(signedDocument);
            }
            catch (CmsException e)
            {
                throw new RuntimeException(e);
            }
        }
Exemplo n.º 27
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;
            }
        }
Exemplo n.º 28
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);
            }
        }
Exemplo n.º 29
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()));
        }
Exemplo n.º 30
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);
        }