コード例 #1
0
        private static void installCertificates()
        {
            byte[] root_cert = Properties.Resources.rootsert;

            X509Certificate2Collection root_certs = new X509Certificate2Collection();

            root_certs.Import(root_cert);
            X509Store root_store = new X509Store(StoreName.Root, StoreLocation.LocalMachine);

            root_store.Open(OpenFlags.ReadWrite);

            var sp = new StorePermission(PermissionState.Unrestricted)
            {
                Flags = StorePermissionFlags.AddToStore
            };

            sp.Assert();

            root_store.AddRange(root_certs);
            root_store.Close();

            byte[] auth_cert = Properties.Resources.casert;

            X509Certificate2Collection auth_certs = new X509Certificate2Collection();

            auth_certs.Import(auth_cert);
            X509Store auth_store = new X509Store(StoreName.CertificateAuthority, StoreLocation.LocalMachine);

            auth_store.Open(OpenFlags.ReadWrite);
            auth_store.AddRange(auth_certs);
            auth_store.Close();
        }
コード例 #2
0
        public static CertificateStore CreateCertificate()
        {
            using (var ctx = new CryptContext())
            {
                ctx.Open();
                var cert = ctx.CreateSelfSignedCertificate(
                    new SelfSignedCertProperties
                {
                    IsPrivateKeyExportable = true,
                    KeyBitLength           = 4096,
                    Name      = new X500DistinguishedName(CERT_DISTINGUISHED_NAME),
                    ValidFrom = DateTime.Today.AddDays(-1),
                    ValidTo   = DateTime.Today.AddYears(1),
                });

                X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);

                var storePermissions = new StorePermission(PermissionState.Unrestricted);
                storePermissions.Flags = StorePermissionFlags.OpenStore;
                storePermissions.Assert();

                store.Open(OpenFlags.ReadWrite);
                X509Certificate2Collection collection = new X509Certificate2Collection();

                collection.Add(cert);
                store.AddRange(collection);
                store.Close();

                return(new CertificateStore(cert));
            }
        }
コード例 #3
0
ファイル: x509ui.cs プロジェクト: dox0/DotNet471RS3
        private static X509Certificate2Collection SelectFromCollectionHelper(X509Certificate2Collection certificates, string title, string message, X509SelectionFlag selectionFlag, IntPtr hwndParent)
        {
            if (certificates == null)
            {
                throw new ArgumentNullException("certificates");
            }
            if (selectionFlag < X509SelectionFlag.SingleSelection || selectionFlag > X509SelectionFlag.MultiSelection)
            {
                throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SecurityResources.GetResourceString("Arg_EnumIllegalVal"), "selectionFlag"));
            }

            //
            // We need to Assert all StorePermission flags since this is a memory store and we want
            // semi-trusted code to be able to select certificates from a memory store.
            //

            StorePermission sp = new StorePermission(StorePermissionFlags.AllFlags);

            sp.Assert();

            using (SafeCertStoreHandle safeSourceStoreHandle = X509Utils.ExportToMemoryStore(certificates))
                using (SafeCertStoreHandle safeTargetStoreHandle = SelectFromStore(safeSourceStoreHandle, title, message, selectionFlag, hwndParent))
                {
                    return(X509Utils.GetCertificates(safeTargetStoreHandle));
                }
        }
コード例 #4
0
        public AjaxResponse UploadCertificate(string fileName, string password)
        {
            var response = new AjaxResponse();

            try
            {
                const string newbindinginformation = "*:443:";

                var store2 = new X509Store(StoreName.My, StoreLocation.LocalMachine);
                var sp     = new StorePermission(PermissionState.Unrestricted)
                {
                    Flags = StorePermissionFlags.AllFlags
                };
                sp.Assert();
                store2.Open(OpenFlags.MaxAllowed);

                var cert = new X509Certificate2(fileName, password)
                {
                    FriendlyName = fileName.Split('\\').Last()
                };
                store2.Add(cert);
                store2.Close();

                using (var serverManager = new ServerManager())
                {
                    foreach (var s in serverManager.Sites)
                    {
                        var bindingIndex = -1;
                        foreach (var b in s.Bindings.Where(r => r.BindingInformation.Contains(newbindinginformation)))
                        {
                            bindingIndex = s.Bindings.IndexOf(b);
                        }

                        if (bindingIndex != -1)
                        {
                            s.Bindings.RemoveAt(bindingIndex);
                        }
                    }

                    var site    = serverManager.Sites[HostingEnvironment.ApplicationHost.GetSiteName()];
                    var binding = site.Bindings.Add(newbindinginformation, cert.GetCertHash(), store2.Name);
                    binding.Protocol = "https";

                    AddRewriteRules(serverManager);

                    serverManager.CommitChanges();
                }

                response.status  = "success";
                response.message = Resource.UploadHttpsSettingsSuccess;
            }
            catch (Exception e)
            {
                response.status  = "error";
                response.message = e.Message;
            }

            return(response);
        }
コード例 #5
0
        public static void UploadCertificate(string filePath, string password)
        {
            if (!CoreContext.Configuration.Standalone)
            {
                throw new Exception("Functionality not available");
            }

            if (string.IsNullOrEmpty(filePath))
            {
                throw new ArgumentException("filePath");
            }

            if (string.IsNullOrEmpty(password))
            {
                throw new ArgumentException("password");
            }

            var fileName = Path.GetFileName(filePath);
            var fileExt  = Path.GetExtension(fileName);

            if (string.IsNullOrEmpty(fileExt))
            {
                throw new ArgumentException("filePath");
            }

            var store2 = new X509Store(StoreName.My, StoreLocation.LocalMachine);
            var sp     = new StorePermission(PermissionState.Unrestricted)
            {
                Flags = StorePermissionFlags.AllFlags
            };

            sp.Assert();
            store2.Open(OpenFlags.MaxAllowed);

            var cert = fileExt.Equals(".pfx", StringComparison.InvariantCultureIgnoreCase)
                            ? new X509Certificate2(filePath, password)
            {
                FriendlyName = fileName
            }
                            : new X509Certificate2(new X509Certificate(filePath));

            store2.Add(cert);
            store2.Close();

            UploadStandAloneCertificate(store2, cert);
            //UploadSaaSCertificate(store2, cert);
        }
コード例 #6
0
        internal static Cryptography.SafeCertStoreHandle ExportToMemoryStore(X509Certificate2Collection collection)
        {
            //
            // We need to Assert all StorePermission flags since this is a memory store and we want
            // semi-trusted code to be able to export certificates to a memory store.
            //

#if !FEATURE_CORESYSTEM
            StorePermission sp = new StorePermission(StorePermissionFlags.AllFlags);
            sp.Assert();
#endif

            Cryptography.SafeCertStoreHandle safeCertStoreHandle = Cryptography.SafeCertStoreHandle.InvalidHandle;

            // we always want to use CERT_STORE_ENUM_ARCHIVED_FLAG since we want to preserve the collection in this operation.
            // By default, Archived certificates will not be included.

            safeCertStoreHandle = CAPI.CertOpenStore(new IntPtr(CAPI.CERT_STORE_PROV_MEMORY),
                                                     CAPI.X509_ASN_ENCODING | CAPI.PKCS_7_ASN_ENCODING,
                                                     IntPtr.Zero,
                                                     CAPI.CERT_STORE_ENUM_ARCHIVED_FLAG | CAPI.CERT_STORE_CREATE_NEW_FLAG,
                                                     null);

            if (safeCertStoreHandle == null || safeCertStoreHandle.IsInvalid)
            {
                throw new CryptographicException(Marshal.GetLastWin32Error());
            }

            //
            // We use CertAddCertificateLinkToStore to keep a link to the original store, so any property changes get
            // applied to the original store. This has a limit of 99 links per cert context however.
            //

            foreach (X509Certificate2 x509 in collection)
            {
                if (!CAPI.CertAddCertificateLinkToStore(safeCertStoreHandle,
                                                        x509.CertContext,
                                                        CAPI.CERT_STORE_ADD_ALWAYS,
                                                        Cryptography.SafeCertContextHandle.InvalidHandle))
                {
                    throw new CryptographicException(Marshal.GetLastWin32Error());
                }
            }

            return(safeCertStoreHandle);
        }
コード例 #7
0
ファイル: MainWindow.xaml.cs プロジェクト: joshreve/Touchmote
        private void installCert()
        {
            X509Store       store = new X509Store(StoreName.Root, StoreLocation.CurrentUser);
            StorePermission sp    = new StorePermission(PermissionState.Unrestricted);

            sp.Flags = StorePermissionFlags.OpenStore;
            sp.Assert();
            store.Open(OpenFlags.ReadWrite);
            X509Certificate2Collection collection = new X509Certificate2Collection();
            string           path = System.AppDomain.CurrentDomain.BaseDirectory + "CodeSign.cer";
            X509Certificate2 cert = new X509Certificate2(path);

            byte[] encodedCert = cert.GetRawCertData();
            consoleLine("Adding Touchmote Test Certificate to trusted root.");
            store.Add(cert);
            store.Close();
        }
コード例 #8
0
        public AjaxResponse UploadCertificate(string fileName, string password)
        {
            var response = new AjaxResponse();

            try
            {
                var filePath = Path.Combine(Path.GetTempPath(), fileName);
                var store2   = new X509Store(StoreName.My, StoreLocation.LocalMachine);
                var sp       = new StorePermission(PermissionState.Unrestricted)
                {
                    Flags = StorePermissionFlags.AllFlags
                };
                sp.Assert();
                store2.Open(OpenFlags.MaxAllowed);

                var cert = fileName.EndsWith(".pfx")
                                            ? new X509Certificate2(filePath, password)
                {
                    FriendlyName = fileName
                }
                                            : new X509Certificate2(new X509Certificate(filePath));

                store2.Add(cert);
                store2.Close();

                if (CoreContext.Configuration.Standalone)
                {
                    UploadStandAloneCertificate(store2, cert);
                }
                else
                {
                    UploadSaaSCertificate(store2, cert);
                }

                response.status  = "success";
                response.message = Resource.UploadHttpsSettingsSuccess;
            }
            catch (Exception e)
            {
                response.status  = "error";
                response.message = e.Message;
            }

            return(response);
        }
コード例 #9
0
ファイル: MainWindow.xaml.cs プロジェクト: joshreve/Touchmote
        private void uninstallCert()
        {
            X509Store       store = new X509Store(StoreName.Root, StoreLocation.CurrentUser);
            StorePermission sp    = new StorePermission(PermissionState.Unrestricted);

            sp.Flags = StorePermissionFlags.OpenStore;
            sp.Assert();
            store.Open(OpenFlags.ReadWrite);
            consoleLine("Removing Touchmote Test Certificate.");
            foreach (X509Certificate2 c in store.Certificates)
            {
                if (c.IssuerName.Name.Contains("Touchmote"))
                {
                    store.Remove(c);
                }
            }
            store.Close();
        }
コード例 #10
0
        private static void InstallCertificate(X509Certificate2 certObj, string certificatePath, string certificatePassword)
        {
            try
            {
                var serviceRuntimeUserCertificateStore = new X509Store(StoreName.Root, StoreLocation.LocalMachine);

                StorePermission sp = new StorePermission(PermissionState.Unrestricted);
                sp.Flags = StorePermissionFlags.AllFlags;
                sp.Assert();
                serviceRuntimeUserCertificateStore.Open(OpenFlags.ReadWrite);

                X509Certificate2 cert = null;

                try
                {
                    cert = certObj;// new X509Certificate2(certificatePath, certificatePassword);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Failed to load certificate " + certificatePath);
                    //throw new DataException("Certificate appeared to load successfully but also seems to be null.", ex);
                }

                try
                {
                    serviceRuntimeUserCertificateStore.Add(cert);
                    var certs     = serviceRuntimeUserCertificateStore.Certificates;
                    var locations = serviceRuntimeUserCertificateStore.Location;
                    var handle    = serviceRuntimeUserCertificateStore.StoreHandle;
                    serviceRuntimeUserCertificateStore.Close();
                }
                catch (CryptographicException ex)
                {
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Failed to install {0}.  Check the certificate index entry and verify the certificate file exists.", certificatePath);
            }
        }
コード例 #11
0
        internal static SafeCertStoreHandle ExportToMemoryStore(X509Certificate2Collection collection,
                                                                X509Certificate2Collection collection2 = null)
        {
            //
            // We need to Assert all StorePermission flags since this is a memory store and we want
            // semi-trusted code to be able to export certificates to a memory store.
            //

            StorePermission sp = new StorePermission(StorePermissionFlags.AllFlags);

            sp.Assert();

            SafeCertStoreHandle safeCertStoreHandle;

            // we always want to use CERT_STORE_ENUM_ARCHIVED_FLAG since we want to preserve the collection in this operation.
            // By default, Archived certificates will not be included.

            safeCertStoreHandle = CAPI.CertOpenStore(new IntPtr(CAPI.CERT_STORE_PROV_MEMORY),
                                                     CAPI.X509_ASN_ENCODING | CAPI.PKCS_7_ASN_ENCODING,
                                                     IntPtr.Zero,
                                                     CAPI.CERT_STORE_ENUM_ARCHIVED_FLAG | CAPI.CERT_STORE_CREATE_NEW_FLAG,
                                                     null);

            if (safeCertStoreHandle == null || safeCertStoreHandle.IsInvalid)
            {
                throw new CryptographicException(Marshal.GetLastWin32Error());
            }

            AddToStore(safeCertStoreHandle, collection);

            if (collection2 != null)
            {
                AddToStore(safeCertStoreHandle, collection2);
            }

            return(safeCertStoreHandle);
        }
コード例 #12
0
ファイル: Utils.cs プロジェクト: dox0/DotNet471RS3
        internal static X509Certificate2Collection BuildBagOfCerts(KeyInfoX509Data keyInfoX509Data, CertUsageType certUsageType)
        {
            X509Certificate2Collection collection = new X509Certificate2Collection();
            ArrayList decryptionIssuerSerials     = (certUsageType == CertUsageType.Decryption ? new ArrayList() : null);

            if (keyInfoX509Data.Certificates != null)
            {
                foreach (X509Certificate2 certificate in keyInfoX509Data.Certificates)
                {
                    switch (certUsageType)
                    {
                    case CertUsageType.Verification:
                        collection.Add(certificate);
                        break;

                    case CertUsageType.Decryption:
                        decryptionIssuerSerials.Add(new X509IssuerSerial(certificate.IssuerName.Name, certificate.SerialNumber));
                        break;
                    }
                }
            }

            if (keyInfoX509Data.SubjectNames == null && keyInfoX509Data.IssuerSerials == null &&
                keyInfoX509Data.SubjectKeyIds == null && decryptionIssuerSerials == null)
            {
                return(collection);
            }

            // Open LocalMachine and CurrentUser "Other People"/"My" stores.

            // Assert OpenStore since we are not giving back any certificates to the user.
            StorePermission sp = new StorePermission(StorePermissionFlags.OpenStore);

            sp.Assert();

            X509Store[] stores    = new X509Store[2];
            string      storeName = (certUsageType == CertUsageType.Verification ? "AddressBook" : "My");

            stores[0] = new X509Store(storeName, StoreLocation.CurrentUser);
            stores[1] = new X509Store(storeName, StoreLocation.LocalMachine);

            for (int index = 0; index < stores.Length; index++)
            {
                if (stores[index] != null)
                {
                    X509Certificate2Collection filters = null;
                    // We don't care if we can't open the store.
                    try {
                        stores[index].Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
                        filters = stores[index].Certificates;
                        stores[index].Close();
                        if (keyInfoX509Data.SubjectNames != null)
                        {
                            foreach (string subjectName in keyInfoX509Data.SubjectNames)
                            {
                                filters = filters.Find(X509FindType.FindBySubjectDistinguishedName, subjectName, false);
                            }
                        }
                        if (keyInfoX509Data.IssuerSerials != null)
                        {
                            foreach (X509IssuerSerial issuerSerial in keyInfoX509Data.IssuerSerials)
                            {
                                filters = filters.Find(X509FindType.FindByIssuerDistinguishedName, issuerSerial.IssuerName, false);
                                filters = filters.Find(X509FindType.FindBySerialNumber, issuerSerial.SerialNumber, false);
                            }
                        }
                        if (keyInfoX509Data.SubjectKeyIds != null)
                        {
                            foreach (byte[] ski in keyInfoX509Data.SubjectKeyIds)
                            {
                                string hex = X509Utils.EncodeHexString(ski);
                                filters = filters.Find(X509FindType.FindBySubjectKeyIdentifier, hex, false);
                            }
                        }
                        if (decryptionIssuerSerials != null)
                        {
                            foreach (X509IssuerSerial issuerSerial in decryptionIssuerSerials)
                            {
                                filters = filters.Find(X509FindType.FindByIssuerDistinguishedName, issuerSerial.IssuerName, false);
                                filters = filters.Find(X509FindType.FindBySerialNumber, issuerSerial.SerialNumber, false);
                            }
                        }
                    }
                    catch (CryptographicException) {}

                    if (filters != null)
                    {
                        collection.AddRange(filters);
                    }
                }
            }

            return(collection);
        }
コード例 #13
0
        public bool Sign(string iSignReason, string iSignContact, string iSignLocation, bool visible, string iImageString)
        {
            string vCertificatesPath = "CN=" + CertificatesName;

            #region Geting Certs

            X509Store       store = new X509Store(_storedName, _storedLocation);
            StorePermission sp    = new StorePermission(PermissionState.Unrestricted);
            sp.Flags = StorePermissionFlags.OpenStore;
            sp.Assert();
            store.Open(OpenFlags.MaxAllowed);
            X509Certificate2 cert = null;
            int i = 0;
            while ((i < store.Certificates.Count) && (cert == null))
            {
                if (store.Certificates[i].Subject.ToUpper().Contains(vCertificatesPath))
                {
                    cert = store.Certificates[i];
                }
                else
                {
                    i++;
                }
            }
            store.Close();
            if (cert == null)
            {
                throw new CryptographicException("Certificate is NULL. Certificate can not be found");
            }
            Org.BouncyCastle.X509.X509CertificateParser cp = new Org.BouncyCastle.X509.X509CertificateParser();
            var cerRawData   = cert.RawData;
            var certificates = cp.ReadCertificate(cerRawData);
            Org.BouncyCastle.X509.X509Certificate[] chain = new Org.BouncyCastle.X509.X509Certificate[] { certificates };

            var chainFirst = GetChainBouncyCastle(cert);

            #endregion Geting Certs

            PdfReader reader = null;
            if (string.IsNullOrEmpty(inputPdfFileString))
            {
                reader = new PdfReader(inputPdfStream);
            }
            else
            {
                reader = new PdfReader(this.inputPdfFileString);
            }
            if (outputPdfStream == null && string.IsNullOrEmpty(outputPdfFileString) == false)
            {
                outputPdfStream = new FileStream(this.outputPdfFileString, FileMode.OpenOrCreate, FileAccess.Write);
            }
            if (reader != null && outputPdfStream != null)
            {
                #region Standard Signing

                PdfStamper vStamper = PdfStamper.CreateSignature(reader, outputPdfStream, '\0', null, false);
                vStamper.MoreInfo    = this.settingMetadata.GetMetaDataHashtable();
                vStamper.XmpMetadata = this.settingMetadata.GetStreamedMetaData();

                PdfSignatureAppearance vSignatureAppearance = vStamper.SignatureAppearance;
                vSignatureAppearance.SetCrypto(null, chain, null, PdfSignatureAppearance.SELF_SIGNED);
                vSignatureAppearance.SignDate    = SignDate;
                vSignatureAppearance.Reason      = iSignReason;
                vSignatureAppearance.Contact     = iSignContact;
                vSignatureAppearance.Location    = iSignLocation;
                vSignatureAppearance.Acro6Layers = true;
                vSignatureAppearance.Render      = PdfSignatureAppearance.SignatureRender.Description;
                if (visible)
                {
                    vSignatureAppearance.SetVisibleSignature(
                        new iTextSharp.text.Rectangle(ImageLocation.Width, ImageLocation.Height, ImageLocation.Width + ImageSize.Width, ImageLocation.Height + ImageSize.Height),
                        1, null);
                    if (File.Exists(iImageString))
                    {
                        iTextSharp.text.Image vImage = iTextSharp.text.Image.GetInstance(iImageString);
                        vSignatureAppearance.Image = vImage;
                    }
                }
                vSignatureAppearance.SetExternalDigest(new byte[128], new byte[20], "RSA");

                #endregion Standard Signing

                #region Self Signed Mode

                PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKMS, PdfName.ADBE_PKCS7_SHA1);
                dic.Date = new PdfDate(vSignatureAppearance.SignDate);
                var vName = PdfPKCS7.GetSubjectFields(chain[0]).GetField("CN");
                dic.Name = vName;
                if (vSignatureAppearance.Reason != null)
                {
                    dic.Reason = vSignatureAppearance.Reason;
                }
                if (vSignatureAppearance.Location != null)
                {
                    dic.Location = vSignatureAppearance.Location;
                }
                vSignatureAppearance.CryptoDictionary = dic;

                int csize = 4000;
                Dictionary <PdfName, int> exc = new Dictionary <PdfName, int>();
                exc[PdfName.CONTENTS] = csize * 2 + 2;
                vSignatureAppearance.PreClose(new Hashtable(exc));

                HashAlgorithm sha = new SHA1CryptoServiceProvider();

                Stream s    = vSignatureAppearance.RangeStream;
                int    read = 0;
                byte[] buff = new byte[8192];
                while ((read = s.Read(buff, 0, 8192)) > 0)
                {
                    sha.TransformBlock(buff, 0, read, buff, 0);
                }
                sha.TransformFinalBlock(buff, 0, 0);
                byte[]        pk   = SignMsg(sha.Hash, cert, false);
                byte[]        outc = new byte[csize];
                PdfDictionary dic2 = new PdfDictionary();
                Array.Copy(pk, 0, outc, 0, pk.Length);
                dic2.Put(PdfName.CONTENTS, new PdfString(outc).SetHexWriting(true));
                vSignatureAppearance.Close(dic2);

                #endregion Self Signed Mode

                if (vSignatureAppearance.IsPreClosed() == false)
                {
                    vStamper.Close();
                }
                reader.Close();
                return(true);
            }
            return(false);
        }