コード例 #1
0
        public void LoadCertificateFromStore()
        {
            var store = new X509Store(StoreName.Root, StoreLocation.CurrentUser);

            try
            {
                store.Open(OpenFlags.ReadOnly);
                var certificates = store.Certificates
                                   .Find(X509FindType.FindBySubjectKeyIdentifier, certificateKey, false);

                if (certificates.Count == 0)
                {
                    useCertificate = false;
                    return;
                }

                var item = certificates[0];
                using (var stream = new MemoryStream(item.Export(X509ContentType.Pfx, certificatePassphrase), false))
                {
                    stream.Position = 0;
                    var result = certificate.LoadFromStreamPFX(stream, certificatePassphrase, (int)stream.Length);
                    if (result != 0)
                    {
                        var message = string.Format("Unable to load certificate \"{0}\". Result: \"{1}\".",
                                                    certificatePath, result);

                        throw new ApplicationException(message);
                    }

                    useCertificate = true;
                }
            }
            catch
            {
                LoadCertificateFromFile();
            }
            finally
            {
                store.Close();
            }
        }
コード例 #2
0
        private static TElX509Certificate LoadCertificate(string certificateName, string certificatePassword)
        {
            // We do not use LoadFromFileAuto or LoadFromBuffer here because it works only on desktop => Invalid Certificate Data on WinCe
            // TODO : deal with PEM & SPC
            using (FileStream fs = new FileStream(certificateName, FileMode.Open))
            {
                TElX509Certificate cert = new TElX509Certificate();
                switch (cert.LoadFromStreamPFX(fs, certificatePassword, 0))
                {
                case 0:
                    return(cert);

                case 7955:     // SB_PKCS12_ERROR_INVALID_PASSWORD
                    throw new HttpException("Invalid certificate password");

                default:
                    throw new HttpException(string.Format("Unable to load the certificate from '{0}'", certificateName));
                }
            }
        }