Exemplo n.º 1
0
 static void Main(string[] args)
 {
     try
     {
         //Friendly name Argument
         if (args.Length > 0)
         {
             _FriendlyName = args[0];
         }
         //Certpath argument
         if (args.Length > 1)
         {
             _CertPath = args[1];
         }
         //Set and open the Store
         _oCurrStore = new StoreClass();
         _oCurrStore.Open(
             CAPICOM_STORE_LOCATION.CAPICOM_LOCAL_MACHINE_STORE,
             _currStoreName,
             CAPICOM_STORE_OPEN_MODE.CAPICOM_STORE_OPEN_EXISTING_ONLY |
             CAPICOM_STORE_OPEN_MODE.CAPICOM_STORE_OPEN_MAXIMUM_ALLOWED);
         //Call the import certificate function
         importCert();
     }
     catch (Exception ex) {
         Console.WriteLine(ex.Message);
         Console.WriteLine(args[0]);
     }
 }
Exemplo n.º 2
0
        private byte[] CoSignBuffer(byte[] data, byte[] signdata)
        {
            X509Certificate2 m_cert = cbCerts.SelectedItem as X509Certificate2;

            if (m_cert == null)
            {
                MessageBox.Show("не найден сертификат!");
                return(null);
            }
            SignedData signedData = new SignedDataClass();
            Utilities  utilities  = new UtilitiesClass();

            byte[] array = data;

            Signer signer = new SignerClass();
            IStore store  = new StoreClass();
            bool   flag2  = false;

            store.Open(CAPICOM_STORE_LOCATION.CAPICOM_CURRENT_USER_STORE, "My", CAPICOM_STORE_OPEN_MODE.CAPICOM_STORE_OPEN_READ_ONLY);
            foreach (ICertificate certificate in store.Certificates)
            {
                if (certificate.Thumbprint == m_cert.Thumbprint)
                {
                    signer.Certificate = certificate;
                    flag2 = true;
                    break;
                }
            }
            if (!flag2)
            {
                throw new Exception("Не удалось найти сертификат подписи!");
            }
            CapiComRCW.Attribute attribute = new AttributeClass();
            attribute.Name  = CAPICOM_ATTRIBUTE.CAPICOM_AUTHENTICATED_ATTRIBUTE_SIGNING_TIME;
            attribute.Value = DateTime.Now.ToUniversalTime();
            signer.AuthenticatedAttributes.Add(attribute);
            byte[] array3;
            byte[] array2 = signdata;
            ((CapiComRCW.ISignedData)signedData).set_Content(utilities.ByteArrayToBinaryString(array));
            signedData.Verify(Convert.ToBase64String(array2), true, CAPICOM_SIGNED_DATA_VERIFY_FLAG.CAPICOM_VERIFY_SIGNATURE_ONLY);
            Store store2 = new StoreClass();

            store2.Open(CAPICOM_STORE_LOCATION.CAPICOM_CURRENT_USER_STORE, "AddressBook", CAPICOM_STORE_OPEN_MODE.CAPICOM_STORE_OPEN_READ_WRITE);
            for (int i = 1; i <= signedData.Signers.Count; i++)
            {
                Signer      signer2 = (Signer)signedData.Signers[i];
                Certificate pVal    = (Certificate)signer2.Certificate;
                store2.Add(pVal);
            }
            store2.Close();
            string s = signedData.CoSign(signer, CAPICOM_ENCODING_TYPE.CAPICOM_ENCODE_BASE64);

            array3 = Convert.FromBase64String(s);
            return(array3);
        }
Exemplo n.º 3
0
 static void Main(string[] args)
 {
     //We take one argument, a starting store name
     if (args.Length > 0)
     {
         _currStoreName = args[0];
     }
     _oCurrStore = new StoreClass();
     _oCurrStore.Open(
         CAPICOM_STORE_LOCATION.CAPICOM_CURRENT_USER_STORE,
         _currStoreName,
         CAPICOM_STORE_OPEN_MODE.CAPICOM_STORE_OPEN_EXISTING_ONLY |
         CAPICOM_STORE_OPEN_MODE.CAPICOM_STORE_OPEN_MAXIMUM_ALLOWED);
     waitForInput();
 }
        public bool AddContactCertificate(string strContactID, X509Certificate cert)
        {
            if (strContactID == null || strContactID.Length == 0)
            {
                throw new ArgumentException("Invalid contact ID", "strContactID");
            }
            if (cert == null)
            {
                throw new ArgumentNullException("cert", "Invalid Contact X509 Certificate");
            }

            // Prevent any attempt to add multiple certificates for a contact
            if (IsContactCertificateInStore(strContactID))
            {
                return(true);
            }

            bool bRetVal = true;

            // Use CAPICOM (v2.0) support to add certificate
            StoreClass store = new StoreClass();

            store.Open(CAPICOM_STORE_LOCATION.CAPICOM_LOCAL_MACHINE_STORE,
                       X509CertificateStore.MyStore,
                       CAPICOM_STORE_OPEN_MODE.CAPICOM_STORE_OPEN_EXISTING_ONLY |
                       CAPICOM_STORE_OPEN_MODE.CAPICOM_STORE_OPEN_MAXIMUM_ALLOWED
                       );

            // Store certificate
            // Convert cert to base64 string
            string strBase64Cert = cert.ToBase64String();
            // Save to temp file
            string       strTempFile = Guid.NewGuid().ToString();
            StreamWriter sw          = new StreamWriter(File.Create(strTempFile));

            sw.Write(strBase64Cert);
            sw.Flush();
            sw.Close();
            // Load cert from temp file
            store.Load(strTempFile, Constants.DEFAULT_CERT_PSWD, CAPICOM_KEY_STORAGE_FLAG.CAPICOM_KEY_STORAGE_DEFAULT | CAPICOM_KEY_STORAGE_FLAG.CAPICOM_KEY_STORAGE_EXPORTABLE);
            // Delete temp file
            File.Delete(strTempFile);
            // Close store
            store.CloseHandle(store.StoreHandle);
            // Return true
            return(bRetVal);
        }
        public X509Certificate FindCertificate()
        {
            oStore = new StoreClass();
            oStore.Open(
                CAPICOM_STORE_LOCATION.CAPICOM_CURRENT_USER_STORE,
                storeName, CAPICOM_STORE_OPEN_MODE.CAPICOM_STORE_OPEN_EXISTING_ONLY |
                CAPICOM_STORE_OPEN_MODE.CAPICOM_STORE_OPEN_READ_ONLY
                );

            oCerts = (Certificates)oStore.Certificates;
            oCerts = (Certificates)oCerts.Find(CAPICOM_CERTIFICATE_FIND_TYPE.CAPICOM_CERTIFICATE_FIND_SUBJECT_NAME, "", false);

            /*oCerts = (Certificates)oCerts.Find(
             *      CAPICOM_CERTIFICATE_FIND_TYPE.CAPICOM_CERTIFICATE_FIND_SUBJECT_NAME, filter, false);*/

//			foreach(Certificate ocert in oCerts)  //Certificates is IEnumerable
//			{
//				ocert.Display();
//			}

            //--- get first cert using indexer, retrieve ICertContext and use from managed code -----
            if (oCerts.Count > 0)
            {
                Certificate firstcert = (Certificate)oCerts[1];
                //firstcert.Display() ;

                ICertContext iCertCntxt = (ICertContext)firstcert;
                int          certcntxt  = iCertCntxt.CertContext;

                IntPtr hCertCntxt = new IntPtr(certcntxt);
                if (hCertCntxt != IntPtr.Zero)
                {
                    //use certcontext from managed code
                    string s = "";
                    s += " CertContext: " + hCertCntxt.ToInt32();
                    X509Certificate foundcert = new X509Certificate(hCertCntxt);
                    s += " subject name: " + foundcert.GetName();
                    s += " serial no: " + foundcert.GetSerialNumberString();
                    s += " hash string:" + foundcert.GetCertHashString();
                    return(foundcert);
                }
            }
            return(null);
        }
        public bool RemoveContactCertificate(string strContactID)
        {
            if (strContactID == null || strContactID.Length == 0)
            {
                throw new ArgumentException("Invalid contact ID", "strContactID");
            }

            // Prevent any attempt to add multiple certificates for a contact
            if (!IsContactCertificateInStore(strContactID))
            {
                return(true);
            }

            bool bRetVal = true;

            // Use CAPICOM (v2.0) support to remove certificate
            StoreClass store = new StoreClass();

            store.Open(CAPICOM_STORE_LOCATION.CAPICOM_LOCAL_MACHINE_STORE,
                       X509CertificateStore.MyStore,
                       CAPICOM_STORE_OPEN_MODE.CAPICOM_STORE_OPEN_EXISTING_ONLY |
                       CAPICOM_STORE_OPEN_MODE.CAPICOM_STORE_OPEN_MAXIMUM_ALLOWED
                       );

            // Remove "CN=" prefix from contact ID
            // Hack because CAPICOM Find by Subject name will not ignore the "CN="
            // unlike Microsoft.Web.Services.Security.X509.X509CertificateStore
            int nStart = strContactID.LastIndexOf("=");

            strContactID = strContactID.Substring(nStart + 1);
            // Find the cert to remove
            Certificates certCol = ((Certificates)store.Certificates).Find(CAPICOM_CERTIFICATE_FIND_TYPE.CAPICOM_CERTIFICATE_FIND_SUBJECT_NAME, strContactID, false);
            IEnumerator  it      = certCol.GetEnumerator();

            while (it.MoveNext())
            {
                store.Remove((Certificate)it.Current);
            }

            // Close store
            store.CloseHandle(store.StoreHandle);
            return(bRetVal);
        }
Exemplo n.º 7
0
        /// <summary>
        /// Loads the Client Certificate from the Certificate Store
        /// </summary>
        /// <param name="certStore"></param>
        /// <param name="isMachineStore"></param>
        /// <param name="subjectsName"></param>
        public void LoadCliCertFromCerStore(string certStore, bool isMachineStore, string subjectsName)
        {
            try
            {
//				Store store = new Store();
//
//				store.Open(isMachineStore ? CAPICOM_STORE_LOCATION.CAPICOM_LOCAL_MACHINE_STORE : CAPICOM_STORE_LOCATION.CAPICOM_CURRENT_USER_STORE,
//					certStore, CAPICOM_STORE_OPEN_MODE.CAPICOM_STORE_OPEN_READ_ONLY);
//
//				int nr = 0;
//				foreach (Certificate cert in store.Certificates)
//				{
//					nr++;
//					if (cert.SubjectName.IndexOf(subjectsName) > 0)
//					{
//						ClientCert = cert;
//						store.Close();
//						return;
//					}
//				}
//				store.Close();

                StoreClass oStore = new StoreClass();
                oStore.Open(
                    CAPICOM_STORE_LOCATION.CAPICOM_CURRENT_USER_STORE,
                    certStore, CAPICOM_STORE_OPEN_MODE.CAPICOM_STORE_OPEN_EXISTING_ONLY |
                    CAPICOM_STORE_OPEN_MODE.CAPICOM_STORE_OPEN_READ_ONLY
                    );

                Certificates oCerts = (Certificates)oStore.Certificates;
                oCerts = (Certificates)oCerts.Find(CAPICOM_CERTIFICATE_FIND_TYPE.CAPICOM_CERTIFICATE_FIND_SUBJECT_NAME, "", false);

                if (oCerts.Count > 0)
                {
                    ClientCert = (Certificate)oCerts[1];
                }
            }
            catch (COMException e)
            {
                throw e;
            }
        }
Exemplo n.º 8
0
        static bool parseCommandLine(String input)
        {
            ArrayList   alArgs = ParseArgs(input);
            Certificate oCert  = null;

            switch ((String)alArgs[0])
            {
            case "cd":
            {
                //This is the 'change directory' command
                String storename;
                if (alArgs.Count > 1)
                {
                    storename = (String)alArgs[1];
                }
                else
                {
                    storename = _currStoreName;                             //reset store name
                }

                if (storename.Equals("..") && _currStoreName.Length > 0)
                {
                    _oCurrStore    = new StoreClass();
                    storename      = null;
                    _currFilter    = null;
                    _currStoreName = "";
                }
                else if (storename.StartsWith("..") && _currStoreName.Length > 0)
                {
                    _oCurrStore    = new StoreClass();
                    _currFilter    = null;
                    storename      = storename.Substring(3, storename.Length - 3);
                    _currStoreName = "";
                }
                else if (storename.Equals(".."))
                {
                    storename = null;
                }
                else if (storename.Equals("\\" + LocalMachine) || storename.Equals("\\lm"))
                {
                    _oCurrStore        = new StoreClass();
                    _currStoreName     = "";
                    storename          = null;
                    _currStoreLocation = LocalMachine;
                    _currFilter        = null;
                }
                else if (storename.Equals("\\" + CurrentUser) || storename.Equals("\\cu"))
                {
                    _oCurrStore        = new StoreClass();
                    _currStoreName     = "";
                    storename          = null;
                    _currStoreLocation = CurrentUser;
                    _currFilter        = null;
                }
                if (storename != null && _currStoreName.Equals(""))
                {
                    try
                    {
                        CAPICOM_STORE_LOCATION OpenMode = CAPICOM_STORE_LOCATION.CAPICOM_CURRENT_USER_STORE;
                        if (_currStoreLocation.Equals(LocalMachine))
                        {
                            OpenMode = CAPICOM_STORE_LOCATION.CAPICOM_LOCAL_MACHINE_STORE;
                        }

                        //Open the store MAX_ALLOWED in case the user wants to import/rem/export
                        //They may not have permission to modify HKLM stores
                        _oCurrStore.Open(OpenMode,
                                         storename,
                                         CAPICOM_STORE_OPEN_MODE.CAPICOM_STORE_OPEN_EXISTING_ONLY |
                                         CAPICOM_STORE_OPEN_MODE.CAPICOM_STORE_OPEN_MAXIMUM_ALLOWED);
                        _currStoreName = storename;
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.Message);
                    }
                }
                return(false);
            }

            case "q":
            case "quit":
            {
                return(true);
            }

            case "h":
            case "help":
            {
                DisplayHelp();

                return(false);
            }

            case "v":
            case "view":
                try
                {
                    oCert = GetCertByIndex(Convert.ToInt32(alArgs[1]));
                    if (oCert != null)
                    {
                        DisplayCertificate(oCert, "");
                    }
                    else
                    {
                        Console.WriteLine("No certificate with that index (" + alArgs[1] + ") could be found.");
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("An error was encountered processing the " + alArgs[0] + " command: " + e.Message);
                }
                break;

            case "y":
            case "display":
                try
                {
                    oCert = GetCertByIndex(Convert.ToInt32(alArgs[1]));
                    if (oCert != null)
                    {
                        oCert.Display();
                    }
                    else
                    {
                        Console.WriteLine("No certificate with that index (" + alArgs[1] + ") could be found.");
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("An error was encountered processing the " + alArgs[0] + " command: " + e.Message);
                }
                break;

            case "rem":
                try
                {
                    oCert = GetCertByIndex(Convert.ToInt32(alArgs[1]));
                    if (oCert != null)
                    {
                        String answer = "n";
                        Console.WriteLine(ToColumn(oCert.GetInfo(CAPICOM_CERT_INFO_TYPE.CAPICOM_CERT_INFO_SUBJECT_SIMPLE_NAME), CERTNAME_LENGTH) +
                                          " " +
                                          ToColumn(oCert.Thumbprint, THUMBPRINT_LENGTH));
                        Console.WriteLine("Issuer: " + oCert.GetInfo(CAPICOM_CERT_INFO_TYPE.CAPICOM_CERT_INFO_ISSUER_SIMPLE_NAME));
                        Console.WriteLine("Validity Period: " + oCert.ValidFromDate + " - " + oCert.ValidToDate);
                        DisplayEKU(oCert.ExtendedKeyUsage().EKUs);
                        Console.WriteLine();
                        Console.Write("Are you sure you want to remove this certificate (y/n)? ");
                        answer = Console.ReadLine();
                        if (!answer.Equals("y"))
                        {
                            break;
                        }

                        if (oCert.HasPrivateKey() && !oCert.PrivateKey.IsHardwareDevice())
                        {
                            oCert.PrivateKey.Delete();
                            Console.WriteLine("The private key was deleted.");
                        }
                        try
                        {
                            _oCurrStore.Remove(oCert);
                            Console.WriteLine("The certificate was removed.");
                        }
                        catch
                        {
                            Console.WriteLine("The certificate could not be removed.");
                        }
                    }
                    else
                    {
                        Console.WriteLine("No certificate with that index (" + alArgs[1] + ") could be found.");
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("An error was encountered processing the " + alArgs[0] + " command: " + e.Message);
                }
                break;

            case "e":
            case "export":
                try
                {
                    oCert = GetCertByIndex(Convert.ToInt32(alArgs[1]));
                    if (oCert != null)
                    {
                        String filename = (String)alArgs[2];
                        if (filename != null)
                        {
                            oCert.Save(filename,
                                       "",
                                       CAPICOM_CERTIFICATE_SAVE_AS_TYPE.CAPICOM_CERTIFICATE_SAVE_AS_CER,
                                       CAPICOM_CERTIFICATE_INCLUDE_OPTION.CAPICOM_CERTIFICATE_INCLUDE_END_ENTITY_ONLY);
                        }
                        else
                        {
                            Console.WriteLine("No filename specified.");
                        }
                    }
                    else
                    {
                        Console.WriteLine("No certificate with that index (" + alArgs[1] + ") could be found.");
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("An error was encountered processing the " + alArgs[0] + " command: " + e.Message);
                }
                break;

            case "i":
            case "import":
                try
                {
                    String filename = null;
                    String password = null;
                    CAPICOM_KEY_STORAGE_FLAG iFlag = CAPICOM_KEY_STORAGE_FLAG.CAPICOM_KEY_STORAGE_DEFAULT;

                    if (alArgs.Count >= 2)
                    {
                        filename = (String)alArgs[1];
                    }
                    if (alArgs.Count >= 3)
                    {
                        password = (String)alArgs[2];
                    }
                    if (alArgs.Count >= 4)
                    {
                        String flag = null;
                        if (alArgs.Count == 4)
                        {
                            password = null;
                            flag     = (String)alArgs[3];
                        }
                        else if (alArgs.Count == 5)
                        {
                            flag = (String)alArgs[4];
                        }
                        if (flag.Equals("e"))
                        {
                            iFlag = CAPICOM_KEY_STORAGE_FLAG.CAPICOM_KEY_STORAGE_EXPORTABLE;
                        }
                        else if (flag.Equals("p"))
                        {
                            iFlag = CAPICOM_KEY_STORAGE_FLAG.CAPICOM_KEY_STORAGE_USER_PROTECTED;
                        }
                        else if (flag.Equals("ep") || flag.Equals("pe"))
                        {
                            iFlag = CAPICOM_KEY_STORAGE_FLAG.CAPICOM_KEY_STORAGE_USER_PROTECTED | CAPICOM_KEY_STORAGE_FLAG.CAPICOM_KEY_STORAGE_EXPORTABLE;
                        }
                    }
                    _oCurrStore.Load(filename, password, iFlag);
                }
                catch (Exception e)
                {
                    Console.WriteLine("An error was encountered processing the " + alArgs[0] + " command: " + e.Message);
                }
                break;

            case "p":
            case "pfxexport":
                try
                {
                    oCert = GetCertByIndex(Convert.ToInt32(alArgs[1]));
                    if (oCert != null)
                    {
                        String filename = (String)alArgs[2];
                        String password = (String)alArgs[3];

                        if (filename != null)
                        {
                            oCert.Save(filename,
                                       password,
                                       CAPICOM_CERTIFICATE_SAVE_AS_TYPE.CAPICOM_CERTIFICATE_SAVE_AS_PFX,
                                       CAPICOM_CERTIFICATE_INCLUDE_OPTION.CAPICOM_CERTIFICATE_INCLUDE_WHOLE_CHAIN);
                        }
                        else
                        {
                            Console.WriteLine("No filename specified.");
                        }
                    }
                    else
                    {
                        Console.WriteLine("No certificate with that index (" + alArgs[1] + ") could be found.");
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("An error was encountered processing the " + alArgs[0] + " command: " + e.Message);
                }
                break;

            case "c":
            case "create":
            case "del":
                try
                {
                    // Opening it is the same whether we're creating or deleting
                    if (alArgs.Count == 1)
                    {
                        Console.WriteLine("Please enter a name for the store");
                        break;
                    }
                    String name = (String)alArgs[1];
                    for (int i = 2; i < alArgs.Count; i++)
                    {
                        name += " " + alArgs[i];
                    }
                    Store newStore = new Store();
                    CAPICOM_STORE_LOCATION storeLoc = CAPICOM_STORE_LOCATION.CAPICOM_CURRENT_USER_STORE;
                    if (_currStoreLocation.Equals(LocalMachine))
                    {
                        storeLoc = CAPICOM_STORE_LOCATION.CAPICOM_LOCAL_MACHINE_STORE;
                    }
                    newStore.Open(storeLoc,
                                  name,
                                  CAPICOM_STORE_OPEN_MODE.CAPICOM_STORE_OPEN_READ_WRITE);

                    // Now delete if that is what was chosen
                    if (alArgs[0].Equals("del"))
                    {
                        if (_currStoreName.Equals(name))
                        {
                            Console.WriteLine("You cannot delete the store you are currently viewing");
                            Console.WriteLine("Please use the <cd> command to change stores first");
                            break;
                        }
                        newStore.Delete();
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("An error was encountered processing the " + alArgs[0] + " command: " + e.Message);
                }
                break;

            case "d":
            case "dir":
            {
                Certificates oCerts;
                Listing      listing = Listing.Brief;

                if ((_currStoreLocation.Equals(CurrentUser) || _currStoreLocation.Equals(LocalMachine)) &&
                    _currStoreName.Length == 0)
                {
                    uint retval  = 0;
                    uint dwFlags = CERT_SYSTEM_STORE_CURRENT_USER;

                    CertEnumSystemStoreCallback StoreCallback = new CertEnumSystemStoreCallback(Storesh.CertEnumSystemStoreCallback);
                    if (_currStoreLocation.Equals(LocalMachine))
                    {
                        dwFlags = CERT_SYSTEM_STORE_LOCAL_MACHINE;
                    }
                    retval = Win32.CertEnumSystemStore(
                        dwFlags,
                        0,
                        _currStoreName,
                        StoreCallback
                        );
                }
                else if (alArgs.Count >= 1)
                {
                    int i = 0;
                    try
                    {
                        _currFilter = _oCurrStore.Certificates.GetEnumerator();
                        for (i = 1; i < alArgs.Count; i++)
                        {
                            String param = ((String)alArgs[i]).ToLower();
                            if (param.Equals("/l") || param.Equals("-l"))
                            {
                                listing = Listing.Long;
                            }
                            else if (param.Equals("/subject") || param.Equals("-subject"))
                            {
                                Object filter = (System.String)alArgs[++i];
                                oCerts = (Certificates)_oCurrStore.Certificates;
                                oCerts = (Certificates)oCerts.Find(CAPICOM_CERTIFICATE_FIND_TYPE.CAPICOM_CERTIFICATE_FIND_SUBJECT_NAME,
                                                                   filter,
                                                                   false);
                                _currFilter = oCerts.GetEnumerator();
                            }
                            else if (param.Equals("/eku") || param.Equals("-eku"))
                            {
                                Object filter = (System.String)alArgs[++i];
                                oCerts = (Certificates)_oCurrStore.Certificates;
                                oCerts = (Certificates)oCerts.Find(CAPICOM_CERTIFICATE_FIND_TYPE.CAPICOM_CERTIFICATE_FIND_APPLICATION_POLICY,
                                                                   filter,
                                                                   false);
                                _currFilter = oCerts.GetEnumerator();
                            }
                            else if (param.Equals("/issuer") || param.Equals("-issuer"))
                            {
                                Object filter = (System.String)alArgs[++i];
                                oCerts = (Certificates)_oCurrStore.Certificates;
                                oCerts = (Certificates)oCerts.Find(CAPICOM_CERTIFICATE_FIND_TYPE.CAPICOM_CERTIFICATE_FIND_ISSUER_NAME,
                                                                   filter,
                                                                   false);
                                _currFilter = oCerts.GetEnumerator();
                            }
                            else if (param.Equals("/sha1") || param.Equals("-sha1"))
                            {
                                String filter = (String)alArgs[++i];
                                oCerts = (Certificates)_oCurrStore.Certificates;
                                oCerts = (Certificates)oCerts.Find(CAPICOM_CERTIFICATE_FIND_TYPE.CAPICOM_CERTIFICATE_FIND_SHA1_HASH,
                                                                   filter,
                                                                   false);
                                _currFilter = oCerts.GetEnumerator();
                            }
                        }
                        i = 1;
                        while (_currFilter.MoveNext() == true)
                        {
                            oCert = (Certificate)_currFilter.Current;
                            Console.Write((i++ + ". ").PadRight(4, ' '));
                            switch (listing)
                            {
                            case Listing.Brief:
                                Console.WriteLine(ToColumn(oCert.GetInfo(CAPICOM_CERT_INFO_TYPE.CAPICOM_CERT_INFO_SUBJECT_SIMPLE_NAME), CERTNAME_LENGTH) +
                                                  " " +
                                                  ToColumn(oCert.ValidToDate.ToString(), VALIDITY_LENGTH) +
                                                  ToColumn(oCert.GetInfo(CAPICOM_CERT_INFO_TYPE.CAPICOM_CERT_INFO_ISSUER_SIMPLE_NAME), CERTNAME_LENGTH));
                                break;

                            case Listing.Long:
                            {
                                Console.WriteLine(ToColumn(oCert.GetInfo(CAPICOM_CERT_INFO_TYPE.CAPICOM_CERT_INFO_SUBJECT_SIMPLE_NAME), CERTNAME_LENGTH) +
                                                  " " +
                                                  ToColumn(oCert.Thumbprint, THUMBPRINT_LENGTH));
                                Console.WriteLine("Issuer: " + oCert.GetInfo(CAPICOM_CERT_INFO_TYPE.CAPICOM_CERT_INFO_ISSUER_SIMPLE_NAME));
                                Console.WriteLine("Validity Period: " + oCert.ValidFromDate + " - " + oCert.ValidToDate);
                                DisplayEKU(oCert.ExtendedKeyUsage().EKUs);
                                Console.WriteLine();
                                break;
                            }
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("An error was encountered: " + e.Message);
                    }
                }
                break;
            }

            default:
                DisplayHelp();
                break;
            }

            return(false);
        }
Exemplo n.º 9
0
        private ICertificate2 GetCert()
        {
            try
            {
                Store store = new StoreClass();
                CAPICOM_STORE_LOCATION storeLocation = CAPICOM_STORE_LOCATION.CAPICOM_CURRENT_USER_STORE;
                NameValueCollection section = (NameValueCollection) ConfigurationManager.GetSection("securitySettings");
                string storeName = null;
                if (section != null)
                {
                    string str2 = section["CAPICOM_STORE_LOCATION"];
                    if (str2 != null)
                    {
                        try
                        {
                            storeLocation = (CAPICOM_STORE_LOCATION) Enum.Parse(typeof(CAPICOM_STORE_LOCATION), str2, true);
                        }
                        catch
                        {
                        }
                        storeName = section["StoreName"];
                    }
                }
                else
                {
                    LoggingService.Error("没有找到Security配置节!");
                }
                storeName = (storeName == null) ? "MY" : storeName;
                store.Open(storeLocation, storeName, CAPICOM_STORE_OPEN_MODE.CAPICOM_STORE_OPEN_MAXIMUM_ALLOWED);
                Certificates certificates = ((ICertificates2) store.Certificates).Select("置信自动化办公系统", "请选择你使用的私有数字证书", false);
                ICertificate2 certificate = (ICertificate2) store.Certificates[1];
                if (!certificate.HasPrivateKey())
                {
                    MessageBox.Show("该证书没有私钥,请确认是否是你的私有数字证书!");
                    return null;
                }
                if (certificate.PublicKey().Algorithm.FriendlyName != "RSA")
                {
                    MessageBox.Show("你选择的证书采用算法不是:RSA算法,不能使用!");
                    return null;
                }
                CspParameters parameters = new CspParameters();
                parameters.KeyContainerName = certificate.PrivateKey.ContainerName;
                parameters.ProviderName = certificate.PrivateKey.ProviderName;
                parameters.ProviderType = Convert.ToInt32(certificate.PrivateKey.ProviderType);
                switch (certificate.PrivateKey.KeySpec)
                {
                    case CAPICOM_KEY_SPEC.CAPICOM_KEY_SPEC_KEYEXCHANGE:
                        parameters.KeyNumber = 1;
                        break;

                    case CAPICOM_KEY_SPEC.CAPICOM_KEY_SPEC_SIGNATURE:
                        parameters.KeyNumber = 2;
                        break;
                }
                if (certificate.PrivateKey.IsMachineKeyset())
                {
                    parameters.Flags = CspProviderFlags.UseMachineKeyStore;
                }
                new RSACryptoServiceProvider(parameters).SignData(Convert.FromBase64String("test"), typeof(SHA1));
                return certificate;
            }
            catch (Exception exception)
            {
                MessageBox.Show("发生错误:" + exception.Message);
                return null;
            }
        }
Exemplo n.º 10
0
        private byte[] SignBuffer(byte[] arr)
        {
            X509Certificate2 m_cert = cbCerts.SelectedItem as X509Certificate2;

            if (m_cert == null)
            {
                MessageBox.Show("не найден сертификат!");
                return(null);
            }
            SignedData signedData = new SignedDataClass();
            Utilities  utilities  = new UtilitiesClass();

            byte[] array = arr;
            //using (FileStream fileStream = new FileStream(sFileIn, FileMode.Open, FileAccess.Read))
            //{
            //    array = new byte[fileStream.Length];
            //    fileStream.Position = 0L;
            //    fileStream.Read(array, 0, (int)fileStream.Length);
            //    fileStream.Close();
            //}
            //byte[] array2 = null;
            //bool flag = false;
            //if (File.Exists(sFileIn + ".sig"))
            //{
            //    flag = true;
            //    using (FileStream fileStream = new FileStream(sFileIn + ".sig", FileMode.Open, FileAccess.Read))
            //    {
            //        array2 = new byte[fileStream.Length];
            //        fileStream.Position = 0L;
            //        fileStream.Read(array2, 0, (int)fileStream.Length);
            //        fileStream.Close();
            //    }
            //}
            Signer signer = new SignerClass();
            IStore store  = new StoreClass();
            bool   flag2  = false;

            store.Open(CAPICOM_STORE_LOCATION.CAPICOM_CURRENT_USER_STORE, "My", CAPICOM_STORE_OPEN_MODE.CAPICOM_STORE_OPEN_READ_ONLY);
            foreach (ICertificate certificate in store.Certificates)
            {
                if (certificate.Thumbprint == m_cert.Thumbprint)
                {
                    signer.Certificate = certificate;
                    flag2 = true;
                    break;
                }
            }
            if (!flag2)
            {
                throw new Exception("Не удалось найти сертификат подписи!");
            }
            CapiComRCW.Attribute attribute = new AttributeClass();
            attribute.Name  = CAPICOM_ATTRIBUTE.CAPICOM_AUTHENTICATED_ATTRIBUTE_SIGNING_TIME;
            attribute.Value = DateTime.Now.ToUniversalTime();
            signer.AuthenticatedAttributes.Add(attribute);
            byte[] array3;
            //if (flag)
            //{
            //    ((CapiComRCW.ISignedData)signedData).set_Content(utilities.ByteArrayToBinaryString(array));
            //    signedData.Verify(Convert.ToBase64String(array2), true, CAPICOM_SIGNED_DATA_VERIFY_FLAG.CAPICOM_VERIFY_SIGNATURE_ONLY);
            //    Store store2 = new StoreClass();
            //    store2.Open(CAPICOM_STORE_LOCATION.CAPICOM_CURRENT_USER_STORE, "AddressBook", CAPICOM_STORE_OPEN_MODE.CAPICOM_STORE_OPEN_READ_WRITE);
            //    for (int i = 1; i <= signedData.Signers.Count; i++)
            //    {
            //        Signer signer2 = (Signer)signedData.Signers[i];
            //        Certificate pVal = (Certificate)signer2.Certificate;
            //        store2.Add(pVal);
            //    }
            //    store2.Close();
            //    string s = signedData.CoSign(signer, CAPICOM_ENCODING_TYPE.CAPICOM_ENCODE_BASE64);
            //    array3 = Convert.FromBase64String(s);
            //}
//            else
            {
                //signedData.Content = utilities.ByteArrayToBinaryString(array);
                ((CapiComRCW.ISignedData)signedData).set_Content(utilities.ByteArrayToBinaryString(array));

                string s = signedData.Sign(signer, true, CAPICOM_ENCODING_TYPE.CAPICOM_ENCODE_BASE64);
                array3 = Convert.FromBase64String(s);
            }
            return(array3);
            //using (FileStream fileStream = new FileStream(sFileIn + ".sig", FileMode.Create, FileAccess.Write))
            //{
            //    fileStream.Write(array3, 0, array3.Length);
            //    fileStream.Close();
            //}
        }
Exemplo n.º 11
0
        private void SignFile(string sFileIn)
        {
            if (Path.GetExtension(sFileIn).ToUpper().Equals(".ZIP"))
            {
                SignZip(sFileIn);
                if (!cbExtSignZIP.Checked)
                {
                    return;
                }
            }
            X509Certificate2 m_cert = cbCerts.SelectedItem as X509Certificate2;

            if (m_cert == null)
            {
                throw new ApplicationException("Сформировать ЭЦП невозможно: не найден действительный сертификат отправителя!");
            }
            SignedData signedData = new SignedDataClass();
            Utilities  utilities  = new UtilitiesClass();

            byte[] array;
            using (FileStream fileStream = new FileStream(sFileIn, FileMode.Open, FileAccess.Read))
            {
                array = new byte[fileStream.Length];
                fileStream.Position = 0L;
                fileStream.Read(array, 0, (int)fileStream.Length);
                fileStream.Close();
            }
            byte[] array2 = null;
            bool   flag   = false;

            if (File.Exists(sFileIn + ".sig"))
            {
                flag = true;
                using (FileStream fileStream = new FileStream(sFileIn + ".sig", FileMode.Open, FileAccess.Read))
                {
                    array2 = new byte[fileStream.Length];
                    fileStream.Position = 0L;
                    fileStream.Read(array2, 0, (int)fileStream.Length);
                    fileStream.Close();
                }
            }
            Signer signer = new SignerClass();
            IStore store  = new StoreClass();
            bool   flag2  = false;

            store.Open(CAPICOM_STORE_LOCATION.CAPICOM_CURRENT_USER_STORE, "My", CAPICOM_STORE_OPEN_MODE.CAPICOM_STORE_OPEN_READ_ONLY);
            foreach (ICertificate certificate in store.Certificates)
            {
                if (certificate.Thumbprint == m_cert.Thumbprint)
                {
                    signer.Certificate = certificate;
                    flag2 = true;
                    break;
                }
            }
            if (!flag2)
            {
                throw new Exception("Не удалось найти сертификат подписи!");
            }
            CapiComRCW.Attribute attribute = new AttributeClass();
            attribute.Name  = CAPICOM_ATTRIBUTE.CAPICOM_AUTHENTICATED_ATTRIBUTE_SIGNING_TIME;
            attribute.Value = DateTime.Now.ToUniversalTime();
            signer.AuthenticatedAttributes.Add(attribute);
            byte[] array3;
            if (flag)
            {
                // signedData.Content = "";

                //signedData.Content = Marshal.PtrToStringBSTR( utilities.ByteArrayToBinaryString(array));
                ((CapiComRCW.ISignedData)signedData).set_Content(utilities.ByteArrayToBinaryString(array));
                try
                {
                    signedData.Verify(Convert.ToBase64String(array2), true, CAPICOM_SIGNED_DATA_VERIFY_FLAG.CAPICOM_VERIFY_SIGNATURE_ONLY);
                }
                catch (Exception e)
                {
                    errlist.Add("Ошибка проверки подписи!" + sFileIn + ":" + e.Message);
                }
                Store store2 = new StoreClass();
                store2.Open(CAPICOM_STORE_LOCATION.CAPICOM_CURRENT_USER_STORE, "AddressBook", CAPICOM_STORE_OPEN_MODE.CAPICOM_STORE_OPEN_READ_WRITE);
                for (int i = 1; i <= signedData.Signers.Count; i++)
                {
                    Signer      signer2 = (Signer)signedData.Signers[i];
                    Certificate pVal    = (Certificate)signer2.Certificate;
                    store2.Add(pVal);
                }
                store2.Close();
                string s = signedData.CoSign(signer, CAPICOM_ENCODING_TYPE.CAPICOM_ENCODE_BASE64);
                array3 = Convert.FromBase64String(s);
            }
            else
            {
                //signedData.Content = utilities.ByteArrayToBinaryString(array);
                ((CapiComRCW.ISignedData)signedData).set_Content(utilities.ByteArrayToBinaryString(array));

                string s = signedData.Sign(signer, true, CAPICOM_ENCODING_TYPE.CAPICOM_ENCODE_BASE64);
                array3 = Convert.FromBase64String(s);
            }
            using (FileStream fileStream = new FileStream(sFileIn + ".sig", FileMode.Create, FileAccess.Write))
            {
                fileStream.Write(array3, 0, array3.Length);
                fileStream.Close();
            }
        }
Exemplo n.º 12
0
 static void Main(string[] args)
 {
     //We take one argument, a starting store name
     if (args.Length > 0)
     {
         _currStoreName = args[0];
     }
     _oCurrStore = new StoreClass();
     _oCurrStore.Open(
         CAPICOM_STORE_LOCATION.CAPICOM_CURRENT_USER_STORE,
         _currStoreName,
         CAPICOM_STORE_OPEN_MODE.CAPICOM_STORE_OPEN_EXISTING_ONLY |
         CAPICOM_STORE_OPEN_MODE.CAPICOM_STORE_OPEN_MAXIMUM_ALLOWED);
     waitForInput();
 }