Inheritance: X509Certificate
コード例 #1
1
        protected Saml2Request UnbindInternal(HttpRequestBase request, Saml2Request saml2RequestResponse, X509Certificate2 signatureValidationCertificate)
        {
            if (request == null)
                throw new ArgumentNullException("request");

            if (saml2RequestResponse == null)
                throw new ArgumentNullException("saml2RequestResponse");

            if (signatureValidationCertificate == null)
            {
                throw new ArgumentNullException("signatureValidationCertificate");
            }
            if (signatureValidationCertificate.PublicKey == null)
            {
                throw new ArgumentException("No Public Key present in Signature Validation Certificate.");
            }
            if (!(signatureValidationCertificate.PublicKey.Key is DSA || signatureValidationCertificate.PublicKey.Key is RSACryptoServiceProvider))
            {
                throw new ArgumentException("The Public Key present in Signature Validation Certificate must be either DSA or RSACryptoServiceProvider.");
            }

            saml2RequestResponse.SignatureValidationCertificate = signatureValidationCertificate;

            return saml2RequestResponse;
        }
コード例 #2
1
        public Client(String host, Int32 port)
        {
            try
            {

                clientName = Dns.GetHostName();

            }
            catch (SocketException se)
            {

                MessageBox.Show("ERROR: Could not retrieve client's DNS hostname.  Please try again." + se.Message + ".", "Client Socket Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;

            }

            serverName = host;
            gamePort = port;
            client = new TcpClient(host, port);
            netStream = client.GetStream();
            reader = new StreamReader(netStream);
            writer = new StreamWriter(netStream);
            ssl = new SslStream(netStream, false, new RemoteCertificateValidationCallback(ValidateCert));
            cert = new X509Certificate2("server.crt");
            ssl.AuthenticateAsClient(serverName);
            writer.AutoFlush = true;
        }
コード例 #3
0
ファイル: FrmTest.cs プロジェクト: odouya/PapdAssistant
        /// <summary>
        /// "选择证书"按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSelectaPfxFile_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();

            ofd.Title       = "请选择证书文件";
            ofd.Multiselect = false;
            ofd.Filter      = "证书文件(*.pfx)|*.pfx";
            if (ofd.ShowDialog() == DialogResult.Cancel)
            {
                return;
            }

            try
            {
                //打开证书
                System.Security.Cryptography.X509Certificates.X509Certificate2 x509 = new System.Security.Cryptography.X509Certificates.X509Certificate2(
                    ofd.FileName,
                    PapdHelper.DEFAULT_PFX_PASSWORD, X509KeyStorageFlags.Exportable);
                MsgBox.ShowInfo("证书是别名:" + x509.SubjectName.Name);
                //x509.Thumbprint;
                //x509.PublicKey.Key.ToXmlString(false);
                GlobalContext.CurrentPfxPrivateKey = x509.PrivateKey.ToXmlString(true);
            }
            catch (Exception ex)
            {
                MsgBox.ShowInfo("证书无效," + ex.Message);
            }
        }
コード例 #4
0
        internal static bool addCertToStore(System.Security.Cryptography.X509Certificates.X509Certificate2 cert, System.Security.Cryptography.X509Certificates.StoreName st, System.Security.Cryptography.X509Certificates.StoreLocation sl)
        {
            bool bRet = false;

            try
            {
                X509Store store = new X509Store(st, sl);
                store.Open(OpenFlags.ReadWrite);
                var certs = store.Certificates.Find(X509FindType.FindBySubjectDistinguishedName, cert.SubjectName.Name, false);

                //Remove existing Certificates
                foreach (X509Certificate2 cer in certs)
                {
                    store.Remove(cer);
                }

                store.Add(cert);

                store.Close();
            }
            catch
            {
            }

            return(bRet);
        }
コード例 #5
0
        public static bool VerifyDocument(string path)
        {
            try
            {
                /*CspParameters parms = new CspParameters(1);
                 * parms.KeyContainerName = selectedcert;
                 * RSACryptoServiceProvider csp = new RSACryptoServiceProvider(parms);*/
                if (selectedcert == null)
                {
                    selectedcert = selectcert();
                }
                RSACryptoServiceProvider csp = (RSACryptoServiceProvider)selectedcert.PublicKey.Key;

                XmlDocument xmldoc = new XmlDocument();
                xmldoc.Load(path);

                SignedXml sxml = new SignedXml(xmldoc);

                XmlNode dsig = xmldoc.GetElementsByTagName("Signature", SignedXml.XmlDsigNamespaceUrl)[0];
                sxml.LoadXml((XmlElement)dsig);

                return(sxml.CheckSignature(csp));
            }
            catch (Exception e)
            {
                //appLog.WriteEntry(e.Message + e.StackTrace, System.Diagnostics.EventLogEntryType.Warning);
                //Console.WriteLine(e.Message + e.TargetSite);
                return(false);
            }
        }
コード例 #6
0
        public X509Certificate2 ConvertCertificate(Org.BouncyCastle.X509.X509Certificate certificate,
                                                   AsymmetricCipherKeyPair subjectKeyPair,
                                                   SecureRandom random)
        {
            // Now to convert the Bouncy Castle certificate to a .NET certificate.
            // See http://web.archive.org/web/20100504192226/http://www.fkollmann.de/v2/post/Creating-certificates-using-BouncyCastle.aspx
            // ...but, basically, we create a PKCS12 store (a .PFX file) in memory, and add the public and private key to that.
            var store = new Pkcs12Store();

            // What Bouncy Castle calls "alias" is the same as what Windows terms the "friendly name".
            string friendlyName = certificate.SubjectDN.ToString();

            // Add the certificate.
            var certificateEntry = new X509CertificateEntry(certificate);

            store.SetCertificateEntry(friendlyName, certificateEntry);

            // Add the private key.
            store.SetKeyEntry(friendlyName, new AsymmetricKeyEntry(subjectKeyPair.Private), new[] { certificateEntry });

            // Convert it to an X509Certificate2 object by saving/loading it from a MemoryStream.
            // It needs a password. Since we'll remove this later, it doesn't particularly matter what we use.
            const string password = "******";
            var          stream   = new MemoryStream();

            store.Save(stream, password.ToCharArray(), random);

            var convertedCertificate =
                new X509Certificate2(stream.ToArray(),
                                     password,
                                     X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);

            return(convertedCertificate);
        }
コード例 #7
0
        public CertificateAndPems LoadCertificate(String issuerFileName, String password)
        {
            // We need to pass 'Exportable', otherwise we can't get the private key.
            var issuerCertificate = new X509Certificate2(issuerFileName, password, X509KeyStorageFlags.Exportable);

            return(new CertificateAndPems(issuerCertificate));
        }
コード例 #8
0
        private static System.Security.Cryptography.X509Certificates.X509Certificate2 GetCert(
            string value,
            StoreName storeName,
            StoreLocation storeLocation,
            X509FindType x509FindType,
            bool validOnly,
            bool hasPrivateKey
            )
        {
            using (var store = new X509Store(storeName, storeLocation))
            {
                store.Open(OpenFlags.ReadOnly);
                X509Certificate2Collection collection = store.Certificates.Find(x509FindType, value, validOnly);
                store.Close();
                if (collection.Count == 0)
                {
                    throw new InvalidOperationException("Service Provider certificate could not be found.");
                }
                if (collection.Count > 1)
                {
                    throw new InvalidOperationException("Multiple Service Provider certificates were found, must only provide one.");
                }
                System.Security.Cryptography.X509Certificates.X509Certificate2 x509Certificate2 = collection[0];

                if (x509Certificate2.PrivateKey == null && hasPrivateKey)
                {
                    throw new InvalidOperationException("The certificate for this service providerhas no private key.");
                }
                return(new System.Security.Cryptography.X509Certificates.X509Certificate2(x509Certificate2));
            }
        }
コード例 #9
0
        public Stream RootCert(bool asPem)
        {
            X509Certificate2 rootCert = CertificateFromSubject(StoreName.Root, StoreLocation.LocalMachine, "DO_NOT_TRUST_WcfBridgeRootCA");

            byte[] response;

            if (rootCert == null)
            {
                WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.InternalServerError;
                response = Encoding.UTF8.GetBytes("Root certificate not found on system");
            }
            else
            {
                WebOperationContext.Current.OutgoingResponse.Headers["Content-Disposition"] = "attachment; filename=\"wcf-root-cert.crt\"";

                if (asPem)
                {
                    WebOperationContext.Current.OutgoingResponse.ContentType = "application/x-pem-file";
                    response = Encoding.ASCII.GetBytes(GetCertificateAsPem(rootCert));
                }
                else
                {
                    WebOperationContext.Current.OutgoingResponse.ContentType = "application/x-x509-ca-cert";
                    response = rootCert.RawData;
                }
            }

            return(new MemoryStream(response));
        }
コード例 #10
0
        public Stream ClientCert(bool asPem)
        {
            X509Certificate2 clientCert = CertificateFromSubject(StoreName.My, StoreLocation.LocalMachine, "WCF Client Certificate");

            byte[] response;

            if (clientCert == null)
            {
                WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.InternalServerError;
                response = Encoding.UTF8.GetBytes("Client certificate not found on system");
            }
            else
            {
                if (asPem)
                {
                    WebOperationContext.Current.OutgoingResponse.Headers["Content-Disposition"] = "attachment; filename=\"wcf-client-cert.crt\"";
                    WebOperationContext.Current.OutgoingResponse.ContentType = "application/x-pem-file";
                    response = Encoding.ASCII.GetBytes(GetCertificateAsPem(clientCert));
                }
                else
                {
                    WebOperationContext.Current.OutgoingResponse.Headers["Content-Disposition"] = "attachment; filename=\"wcf-client-cert.pfx\"";
                    WebOperationContext.Current.OutgoingResponse.ContentType = "application/x-pkcs12";
                    response = clientCert.Export(X509ContentType.Pfx, "test");
                }
            }

            return(new MemoryStream(response));
        }
コード例 #11
0
        public static string GetCertificateAsPem(X509Certificate2 certificate)
        {
            string base64String = Convert.ToBase64String(certificate.RawData);

            const string header = "-----BEGIN CERTIFICATE-----\n";
            const string footer = "-----END CERTIFICATE-----";

            StringBuilder builder = new StringBuilder(base64String.Length + header.Length + footer.Length);

            int base64StringIndex = 0;

            builder.Append(header);
            while (base64StringIndex < base64String.Length)
            {
                int charactersToAppend = Math.Min(64, base64String.Length - base64StringIndex);

                builder.Append(base64String, base64StringIndex, charactersToAppend);

                // PEM dictates that this must be a \n, not OS-dependent
                builder.Append('\n');

                base64StringIndex += charactersToAppend;
            }

            builder.Append(footer);

            return(builder.ToString());
        }
コード例 #12
0
        public Stream MachineCert(bool asPem)
        {
            X509Certificate2 machineCert = CertificateFromFriendlyName(StoreName.My, StoreLocation.LocalMachine, "WCF Bridge - Machine certificate generated by the CertificateManager");

            byte[] response;

            if (machineCert == null)
            {
                WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.InternalServerError;
                response = Encoding.UTF8.GetBytes("Machine certificate not found on system");
            }
            else
            {
                WebOperationContext.Current.OutgoingResponse.Headers["Content-Disposition"] = "attachment; filename=\"wcf-machine-cert.crt\"";

                if (asPem)
                {
                    WebOperationContext.Current.OutgoingResponse.ContentType = "application/x-pem-file";
                    response = Encoding.ASCII.GetBytes(GetCertificateAsPem(machineCert));
                }
                else
                {
                    WebOperationContext.Current.OutgoingResponse.ContentType = "application/x-x509-user-cert";
                    response = machineCert.RawData;
                }
            }

            return(new MemoryStream(response));
        }
コード例 #13
0
        public Stream PeerCert(bool asPem)
        {
            X509Certificate2 peerCert = CertificateFromFriendlyName(StoreName.TrustedPeople, StoreLocation.LocalMachine, "WCF Bridge - UserPeerTrustCertificateResource");

            byte[] response;

            if (peerCert == null)
            {
                WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.InternalServerError;
                response = Encoding.UTF8.GetBytes("Peer certificate not found on system");
            }
            else
            {
                if (asPem)
                {
                    WebOperationContext.Current.OutgoingResponse.Headers["Content-Disposition"] = "attachment; filename=\"wcf-peer-cert.crt\"";
                    WebOperationContext.Current.OutgoingResponse.ContentType = "application/x-pem-file";
                    response = Encoding.ASCII.GetBytes(GetCertificateAsPem(peerCert));
                }
                else
                {
                    WebOperationContext.Current.OutgoingResponse.Headers["Content-Disposition"] = "attachment; filename=\"wcf-peer-cert.pfx\"";
                    WebOperationContext.Current.OutgoingResponse.ContentType = "application/x-pkcs12";
                    response = peerCert.Export(X509ContentType.Pfx, "test");
                }
            }

            return(new MemoryStream(response));
        }
コード例 #14
0
        private bool LoadCertificateByThumbprint(string thumbprint)
        {
            thumbprint = thumbprint.Replace(" ", "").ToUpperInvariant();
            StoreName storeName = StoreName.My;
            StoreLocation storeLocation = StoreLocation.LocalMachine;
            X509Store store = new X509Store(storeName, storeLocation);

            try
            {
                store.Open(OpenFlags.ReadOnly);

                foreach (var cert in store.Certificates)
                {
                    if (cert.HasPrivateKey == false)
                        continue;

                    if (String.Compare(cert.Thumbprint, thumbprint) == 0)
                    {
                        _certificate = cert;
                        break;
                    }
                }
            }
            finally
            {
                store.Close();
            }

            if (_certificate == null)
            {
                throw new InvalidOperationException("The certificate with the thumbprint " + thumbprint + " could not be found.");
            }

            return true;
        }
コード例 #15
0
        public Task AuthenticateAsClient(X509Certificate2 certificate)
        {
            var ssl = new SslStream(Stream, false, (sender, x509Certificate, chain, errors) =>
            {
                if (errors.HasFlag(SslPolicyErrors.RemoteCertificateNameMismatch))
                {
                    return true;
                }

                // if (errors == SslPolicyErrors.None)
                //return true;
                return true;
            }, null);

            var tempStream = new SslStreamWrapper(ssl);
            Stream = tempStream;

            Func<AsyncCallback, object, IAsyncResult> begin =
                (cb, s) => ssl.BeginAuthenticateAsClient(this.RemoteIpAddress,
                    new X509Certificate2Collection(certificate),SslProtocols.Tls, false, cb, s);

            var task = Task.Factory.FromAsync(begin, ssl.EndAuthenticateAsClient, null);
           
            return task;
        }
コード例 #16
0
ファイル: X509ChainElement.cs プロジェクト: nlhepler/mono
		// constructors

		// only accessible from X509Chain.ChainElements
		internal X509ChainElement (X509Certificate2 certificate)
		{
			this.certificate = certificate;
			// so far String.Empty is the only thing I've seen. 
			// The interesting stuff is inside X509ChainStatus.Information
			info = String.Empty;
		}
コード例 #17
0
        public void Decrypt(XmlDocument document, X509Certificate2 encryptionCert)
        {
            var assertion = document.FindChild(EncryptedAssertion);
            if (assertion == null) return; // Not encrypted, shame on them.

            var data = document.EncryptedChild("EncryptedData");
            var keyElement = assertion.EncryptedChild("EncryptedKey");

            var encryptedData = new EncryptedData();
            encryptedData.LoadXml(data);

            var encryptedKey = new EncryptedKey();
            encryptedKey.LoadXml(keyElement);

            var encryptedXml = new EncryptedXml(document);

            // Get encryption secret key used by decrypting with the encryption certificate's private key
            var secretKey = GetSecretKey(encryptedKey, encryptionCert.PrivateKey);

            // Seed the decryption algorithm with secret key and then decrypt
            var algorithm = GetSymmetricBlockEncryptionAlgorithm(encryptedData.EncryptionMethod.KeyAlgorithm);
            algorithm.Key = secretKey;
            var decryptedBytes = encryptedXml.DecryptData(encryptedData, algorithm);

            // Put decrypted xml elements back into the document in place of the encrypted data
            encryptedXml.ReplaceData(assertion, decryptedBytes);
        }
コード例 #18
0
ファイル: CustomAction.cs プロジェクト: uw-it-cte/fog-client
        public static ActionResult InstallCert(Session session)
        {
            var cert = RSA.GetCACertificate();
            if (cert != null) return ActionResult.Success;

            var tempDirectory = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());

            Configuration.ServerAddress = Configuration.ServerAddress.Replace("https://", "http://");
            var keyPath = string.Format("{0}ca.cert.der", tempDirectory);
            var downloaded = Communication.DownloadFile("/management/other/ca.cert.der", keyPath);
            if (!downloaded)
            {
                DisplayMSIError(session, "Failed to download CA certificate");
                return ActionResult.Failure;
            }

            try
            {
                cert = new X509Certificate2(keyPath);
                var store = new X509Store(StoreName.Root, StoreLocation.LocalMachine);
                store.Open(OpenFlags.ReadWrite);
                store.Add(cert);

                store.Close();
                return ActionResult.Success;
            }
            catch (Exception ex)
            {
                DisplayMSIError(session, "Unable to install CA certificate: " + ex.Message);
                return ActionResult.Failure;
            }
        }
コード例 #19
0
 public AzureDiscovery(string subscriptionId, X509Certificate2 certificate, IProvisioningObserver observer = null)
 {
     _subscriptionId = subscriptionId;
     _certificate = certificate;
     _observer = observer;
     _policies = new RetryPolicies(observer);
 }
コード例 #20
0
        public int Add(X509Certificate2 certificate)
        {
            if (certificate == null)
                throw new ArgumentNullException("certificate");

            return List.Add(certificate);
        }
        public void CreateWebRequest_returns_request_with_xml_contenttype()
        {
            var certificate = new X509Certificate2();

            var request = ServiceManagementRequest.CreateWebRequest(new Uri("http://foo.bar.baz"), certificate);
            Assert.AreEqual("application/xml", request.ContentType);
        }
コード例 #22
0
        /// <summary>
        /// Create Saml2 based Metadata
        /// </summary>
        /// <returns></returns>
        public EntityDescriptor CreateMetadata()
        {
            _entityId = ConfigurationRepository.Global.IssuerUri;

            _signingCertificate = ConfigurationRepository.Keys.SigningCertificate;

            var descriptor = new EntityDescriptor(new Microsoft.IdentityModel.Protocols.WSFederation.Metadata.EntityId(_entityId));

            var role = new ServiceProviderSingleSignOnDescriptor() { WantAssertionsSigned = true, AuthenticationRequestsSigned = true };

            if (_signingCertificate != null)
            {
                Microsoft.IdentityModel.Protocols.WSFederation.Metadata.KeyDescriptor keyDescriptor = CreateKeyDescriptor(_signingCertificate);
                keyDescriptor.Use = Microsoft.IdentityModel.Protocols.WSFederation.Metadata.KeyType.Signing;
                role.Keys.Add(keyDescriptor);
            }

            role.ProtocolsSupported.Add(new Uri("urn:oasis:names:tc:SAML:2.0:protocol"));

            role.AssertionConsumerService.Add(0, new IndexedProtocolEndpoint(0, ProtocolBindings.HttpPost, new Uri(_endpoints.Saml2ASTPost.AbsoluteUri)) { IsDefault = true });
            role.SingleLogoutServices.Add(new ProtocolEndpoint(ProtocolBindings.HttpPost, new Uri(_endpoints.Saml2SLOPOST.AbsoluteUri)) { ResponseLocation = new Uri(_endpoints.Saml2SLOPostResponse.AbsoluteUri) });

            //
            // Artifact binding and single logout is only supported if there is a signing cerificate.
            //
            if (_signingCertificate != null)
            {
                role.AssertionConsumerService.Add(1, new IndexedProtocolEndpoint(1, ProtocolBindings.HttpArtifact, new Uri(_endpoints.Saml2ASTArtifact.AbsoluteUri)));
                role.AssertionConsumerService.Add(2, new IndexedProtocolEndpoint(2, ProtocolBindings.HttpRedirect, new Uri(_endpoints.Saml2ASTRedirect.AbsoluteUri)));
                role.SingleLogoutServices.Add(new ProtocolEndpoint(ProtocolBindings.HttpRedirect, new Uri(_endpoints.Saml2SLORedirect.AbsoluteUri)) { ResponseLocation = new Uri(_endpoints.Saml2SLORedirectResponse.AbsoluteUri) });
            }

            descriptor.RoleDescriptors.Add(role);
            return descriptor;
        }
        internal AzureHDInsightSubscriptionResolverSimulator()
        {
            var certificate = new X509Certificate2(Convert.FromBase64String(IntegrationTestBase.TestCredentials.Certificate), string.Empty);
            AzureSession.DataStore.AddCertificate(certificate);
            ProfileClient profileClient = new ProfileClient(new AzureSMProfile(Path.Combine(AzureSession.ProfileDirectory, AzureSession.ProfileFile)));
            profileClient.Profile.Accounts[certificate.Thumbprint] = new AzureAccount
            {
                Id = certificate.Thumbprint,
                Type = AzureAccount.AccountType.Certificate,
                Properties =
                    new Dictionary<AzureAccount.Property, string>
                    {
                        {
                            AzureAccount.Property.Subscriptions,
                            IntegrationTestBase.TestCredentials.SubscriptionId.ToString()
                        }
                    }
            };
            profileClient.Profile.Save();

            this.knownSubscriptions = new AzureSubscription[]
                {
                    new AzureSubscription()
                        {
                            Id = IntegrationTestBase.TestCredentials.SubscriptionId,
                            Account = certificate.Thumbprint,
                            Environment = EnvironmentName.AzureCloud
                        }, 
                };
        }
コード例 #24
0
        /// <summary>
        /// Create a service connection to google.
        /// </summary>
        /// <param name="userEmail">The API email to use for authentication.</param>
        /// <param name="gService">The type of service to connect to.</param>
        /// <returns>Returns an open connection to the google api service, or null.</returns>
        private static BaseClientService BuildService(string userEmail, GoogleServices gService = GoogleServices.Directory)
        {
            X509Certificate2 certificate = new X509Certificate2(Properties.Resources.gsd_api,"notasecret", X509KeyStorageFlags.Exportable);

            ServiceAccountCredential credential = new ServiceAccountCredential(
                new ServiceAccountCredential.Initializer(SERVICE_ACCOUNT_EMAIL)
                {
                    Scopes = Scopes,
                    User = userEmail
                }.FromCertificate(certificate));

            switch (gService)
            {
                case GoogleServices.Directory:
                    DirectoryService directoryService = new DirectoryService(new BaseClientService.Initializer()
                        {
                            HttpClientInitializer = credential,
                            ApplicationName = "GSD GAMS",
                        });
                    return directoryService;
                case GoogleServices.Drive:
                    DriveService driveService = new DriveService(new BaseClientService.Initializer()
                        {
                            HttpClientInitializer = credential,
                            ApplicationName = "GSD GAMS",
                        });
                    return driveService;
            }
            return null;
        }
コード例 #25
0
 public AzureCurrentDeployment(string deploymentPrivateId, string subscriptionId, X509Certificate2 certificate, IProvisioningObserver observer = null)
 {
     _subscriptionId = subscriptionId;
     _certificate = certificate;
     _deploymentPrivateId = deploymentPrivateId;
     _observer = observer;
 }
コード例 #26
0
        /// <summary>
        /// Encrypts the DecryptedPassword using the EncryptionAlgorithm and places the result in Password
        /// </summary>
        public override void Encrypt(X509Certificate2 certificate, byte[] senderNonce, string securityPolicyUri)
        {
            if (m_decryptedPassword == null)
            {
                m_password = null;
                return;
            }

            // handle no encryption.
            if (String.IsNullOrEmpty(securityPolicyUri) || securityPolicyUri == SecurityPolicies.None)
            {
                m_password = new UTF8Encoding().GetBytes(m_decryptedPassword);
                m_encryptionAlgorithm = null;
                return;
            }
            
            // encrypt the password.
            byte[] dataToEncrypt = Utils.Append(new UTF8Encoding().GetBytes(m_decryptedPassword), senderNonce);

            EncryptedData encryptedData = SecurityPolicies.Encrypt(
                certificate,
                securityPolicyUri,
                dataToEncrypt);
                        
            m_password = encryptedData.Data;
            m_encryptionAlgorithm = encryptedData.Algorithm; 
        }
コード例 #27
0
        public Certificate(X509Certificate2 cert)
        {
            if (cert == null)
            {
                throw new ArgumentNullException("cert");
            }

            certificate = cert;

            KeyAlgorithm = certificate.GetKeyAlgorithm();
            HasPrivateKey = certificate.HasPrivateKey;
            SerialNumber = certificate.SerialNumber;
            Thumbprint = certificate.Thumbprint;
            FriendlyName = certificate.FriendlyName;// !string.IsNullOrWhiteSpace(_certificate.FriendlyName) ? _certificate.FriendlyName : string.Format("[{0}]\t[{1}]", _certificate.Issuer, _certificate.Subject);
            Subject = certificate.Subject;
            EffectiveDate = certificate.NotBefore;
            ExpirationDate = certificate.NotAfter;
            Format = certificate.GetFormat();
            Issuer = certificate.Issuer;
            SignatureAlgorithm = certificate.SignatureAlgorithm.FriendlyName;
            Version = certificate.Version.ToString();

            Extentions = new List<string>();
            foreach (X509Extension ext in certificate.Extensions)
            {
                Extentions.Add(ext.Format(false));
            }
        }
コード例 #28
0
 public SignatureProcessor(X509Certificate2 certificate, ProtocolSettings discoveryInfo)
 {
     this.Certificate = certificate;
     this.discoveryInfo = discoveryInfo;
     this.SHA1SignatureName = ProtocolStrings.SignatureAlgorithmSHA1Uri;
     this.references = new List<ReferenceEntry>();
 }
コード例 #29
0
 public static IGatewayServiceManagement CreateGatewayManagementChannel(Binding binding, Uri remoteUri, X509Certificate2 cert)
 {
     WebChannelFactory<IGatewayServiceManagement> factory = new WebChannelFactory<IGatewayServiceManagement>(binding, remoteUri);
     factory.Endpoint.Behaviors.Add(new ServiceManagementClientOutputMessageInspector());
     factory.Credentials.ClientCertificate.Certificate = cert;
     return factory.CreateChannel();
 }
コード例 #30
0
        internal X509CertificateEndpointIdentity(XmlDictionaryReader reader)
        {
            if (reader == null)
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader");

            reader.MoveToContent();
            if (reader.IsEmptyElement)
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.Format(SR.UnexpectedEmptyElementExpectingClaim, XD.AddressingDictionary.X509v3Certificate.Value, XD.AddressingDictionary.IdentityExtensionNamespace.Value)));

            reader.ReadStartElement(XD.XmlSignatureDictionary.X509Data, XD.XmlSignatureDictionary.Namespace);
            while (reader.IsStartElement(XD.XmlSignatureDictionary.X509Certificate, XD.XmlSignatureDictionary.Namespace))
            {
                reader.MoveToContent();
                X509Certificate2 certificate = new X509Certificate2(Convert.FromBase64String(reader.ReadContentAsString()));
                if (certificateCollection.Count == 0)
                {
                    // This is the first certificate. We assume this as the primary 
                    // certificate and initialize the base class.
                    Initialize(new Claim(ClaimTypes.Thumbprint, certificate.GetCertHash(), Rights.PossessProperty));
                }

                certificateCollection.Add(certificate);
            }

            reader.ReadEndElement();

            if (certificateCollection.Count == 0)
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.Format(SR.UnexpectedEmptyElementExpectingClaim, XD.AddressingDictionary.X509v3Certificate.Value, XD.AddressingDictionary.IdentityExtensionNamespace.Value)));
        }
コード例 #31
0
        public string assinarEmLote(string xml, X509Certificate2 certificado)
        {

            XmlDocument doc = new XmlDocument();
            doc.PreserveWhitespace = false;
            doc.LoadXml(xml);

            XmlNodeList atributos = doc.ChildNodes.Item(0).ChildNodes;

            for ( int count = 0; count < atributos.Count; count++ )
            {
                if (!atributos.Item(count).Name.Equals("RPS"))
                    continue;

                XmlNode rpsNode = atributos.Item(count);

                string referencia = DefinirReferenciaParaAssinaturaRPS(rpsNode);

                string referenciaCriptografada = CriptografarReferencia(referencia, certificado);

                rpsNode.ChildNodes.Item(0).InnerText = referenciaCriptografada;
            }
            
            return doc.OuterXml;
        }
コード例 #32
0
        private JsonWebSecurityTokenHandler GetSecurityTokenHandler(string audience,
            string authMetadataEndpoint,
            X509Certificate2 currentCertificate)
        {
            JsonWebSecurityTokenHandler jsonTokenHandler = new JsonWebSecurityTokenHandler();
            jsonTokenHandler.Configuration = new Microsoft.IdentityModel.Tokens.SecurityTokenHandlerConfiguration();

            jsonTokenHandler.Configuration.AudienceRestriction = new Microsoft.IdentityModel.Tokens.AudienceRestriction(AudienceUriMode.Always);
            jsonTokenHandler.Configuration.AudienceRestriction.AllowedAudienceUris.Add(
              new Uri(audience, UriKind.RelativeOrAbsolute));

            jsonTokenHandler.Configuration.CertificateValidator = X509CertificateValidator.None;

            jsonTokenHandler.Configuration.IssuerTokenResolver =
              SecurityTokenResolver.CreateDefaultSecurityTokenResolver(
                new ReadOnlyCollection<SecurityToken>(new List<SecurityToken>(
                  new SecurityToken[]
            {
              new X509SecurityToken(currentCertificate)
            })), false);

            Microsoft.IdentityModel.Tokens.ConfigurationBasedIssuerNameRegistry issuerNameRegistry =
                new Microsoft.IdentityModel.Tokens.ConfigurationBasedIssuerNameRegistry();
            issuerNameRegistry.AddTrustedIssuer(currentCertificate.Thumbprint, Config.ExchangeApplicationIdentifier);
            jsonTokenHandler.Configuration.IssuerNameRegistry = issuerNameRegistry;

            return jsonTokenHandler;
        }
コード例 #33
0
 /// <summary>
 /// Method to submit the request to create new storage account and return request token.
 /// </summary>
 /// <param name="subscriptionId">Subscription id</param>
 /// <param name="cert">Auth certificate</param>
 /// <param name="input">Input required to create new storage acc</param>
 /// <returns>Token to track the progress of storage account creation</returns>
 public static string CreateStorageAcc(string subscriptionId, CreateStorageServiceInput input, X509Certificate2 cert)
 {
     ClientOutputMessageInspector messageInspector;
     IServiceManagement serviceManager = ServiceInitializer.Get(cert, out messageInspector);
     serviceManager.CreateStorageAccount(subscriptionId, input);
     return messageInspector.ResponseMessage.Headers["x-ms-request-id"];
 }
コード例 #34
0
        public SslServer(X509Certificate2 cert, bool certRequired, SslProtocols enabledProt, bool expectedExcep)
        {
            certificate = cert;
            clientCertificateRequired = certRequired;
            enabledSslProtocols = enabledProt;
            expectedException = expectedExcep;

            if (!certificate.HasPrivateKey)
            {
                Console.WriteLine("ERROR: The cerfiticate does not have a private key.");
                throw new Exception("No Private Key in the certificate file");
            }

            //Get the IPV4 address on this machine which is all that the MF devices support.
            foreach (IPAddress address in Dns.GetHostAddresses(Dns.GetHostName()))
            {
                if (address.AddressFamily == AddressFamily.InterNetwork)
                {
                    ipAddress = address;
                    break;
                }
            }

            if (ipAddress == null)
                throw new Exception("No IPV4 address found.");

            //Console.WriteLine("ipAddress is: " + ipAddress.ToString());
            //Console.WriteLine("port          is: " + port.ToString());
        }
コード例 #35
0
ファイル: Startup.cs プロジェクト: Charmatzis/IT4GOV
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            var cert = new X509Certificate2(Path.Combine(_environment.ApplicationBasePath, "idsrv4test.pfx"), "idsrv3test");
            var builder = services.AddIdentityServer(options =>
        {
                options.SigningCertificate = cert;
            });
            
            builder.AddInMemoryClients(Clients.Get());
            builder.AddInMemoryScopes(Scopes.Get());
            builder.AddInMemoryUsers(Users.Get());

            builder.AddCustomGrantValidator<CustomGrantValidator>();


            // for the UI
            services
                .AddMvc()
                .AddRazorOptions(razor =>
                {
                    razor.ViewLocationExpanders.Add(new CustomViewLocationExpander());
                });
            services.AddTransient<UI.Login.LoginService>();
            services.AddTransient<UI.SignUp.SignUpService>();
            services.AddTransient<ISmsSender, MessageServices>();
            services.Configure<ASPmsSercetCredentials>(Configuration);



        }
コード例 #36
0
        private static string GetSubjectKeyIdentifier(X509Certificate2 certificate)
        {
            const string SubjectKeyIdentifierOid = "2.5.29.14";
            var extension = certificate.Extensions[SubjectKeyIdentifierOid] as X509SubjectKeyIdentifierExtension;

            return extension == null ? null : extension.SubjectKeyIdentifier;
        }
        private static IAppBuilder ConfigureMiddleware(this IAppBuilder app, string issuerName, X509Certificate2 signingCertificate, string authenticationType)
        {
            if (string.IsNullOrWhiteSpace(issuerName)) throw new ArgumentNullException("issuerName");
            if (signingCertificate == null) throw new ArgumentNullException("signingCertificate");

            var audience = issuerName;

            if (!audience.EndsWith("/"))
            {
                audience += "/";
            }

            audience += "resources";

            app.UseJwtBearerAuthentication(new Microsoft.Owin.Security.Jwt.JwtBearerAuthenticationOptions
            {
                AuthenticationType = authenticationType,

                AllowedAudiences = new[] { audience },
                IssuerSecurityTokenProviders = new[] 
                        {
                            new X509CertificateSecurityTokenProvider(
                                issuerName,
                                signingCertificate)
                        }
            });

            return app;
        }
コード例 #38
0
        public async Task GetServiceInfo()
        {
            var clientCertificate = new X509Certificate2(@"Certs\testwebapplication.pfx", "password");
            this.appConfig.ActiveDirectoryClientCertificate = clientCertificate;
            this.appConfig.ActiveDirectoryServiceEndpointUrl = "https://service/";

            var serviceInfo = await this.serviceInfoProvider.GetServiceInfo(
                this.appConfig,
                this.credentialCache.Object,
                this.httpProvider.Object,
                ClientType.Business) as AdalServiceInfo;

            Assert.IsNotNull(serviceInfo, "Unexpected service info type.");

            var authenticationProvider = serviceInfo.AuthenticationProvider as AdalAuthenticationProvider;
            Assert.IsNotNull(authenticationProvider, "Unexpected authentication provider type.");

            Assert.AreEqual(serviceInfo, authenticationProvider.ServiceInfo, "Unexpected service info set on authentication provider.");

            Assert.AreEqual(this.appConfig.ActiveDirectoryAppId, serviceInfo.AppId, "Unexpected app ID set.");
            Assert.AreEqual(this.credentialCache.Object, serviceInfo.CredentialCache, "Unexpected credential cache set.");
            Assert.AreEqual(this.httpProvider.Object, serviceInfo.HttpProvider, "Unexpected HTTP provider set.");
            Assert.AreEqual(this.appConfig.ActiveDirectoryClientSecret, serviceInfo.ClientSecret, "Unexpected client secret set.");
            Assert.AreEqual(this.appConfig.ActiveDirectoryReturnUrl, serviceInfo.ReturnUrl, "Unexpected return URL set.");
            Assert.AreEqual(clientCertificate, serviceInfo.ClientCertificate, "Unexpected certificate set.");
            Assert.AreEqual(this.serviceInfoProvider.UserSignInName, serviceInfo.UserId, "Unexpected user ID set.");
            Assert.AreEqual(this.appConfig.ActiveDirectoryServiceEndpointUrl, serviceInfo.BaseUrl, "Unexpected base URL set.");
            Assert.IsNull(serviceInfo.WebAuthenticationUi, "Unexpected web UI set.");
        }
 private static void ValidateCertificate(X509Certificate2 certificate)
 {
     if (certificate == null)
     {
         throw new ArgumentException("Certificate is required", nameof(certificate));
     }
     if (!certificate.HasPrivateKey)
     {
         throw new ArgumentException("Certificate has no private key and cannot be used for token signing", nameof(certificate));
     }
     try
     {
         // ReSharper disable once UnusedVariable
         var pk = certificate.PrivateKey;
     }
     catch (Exception e)
     {
         throw new ArgumentException(
             "Certificate has a private key, but it cannot be accessed. " +
             "Either user account has no permission to access private key or this is a CNG certificate. " +
             "Only CSP certificates are fully supported by X509Certificate2.",
             nameof(certificate),
             e);
     }
 }
コード例 #40
0
    public DeploymentServerCertificateValidator(X509Certificate2 allowedCertificate) {
      if (allowedCertificate == null) {
        throw new ArgumentNullException("allowedCertificate");
      }

      this.allowedCertificate = allowedCertificate;
    }
コード例 #41
0
ファイル: CrlCache.cs プロジェクト: nnyamhon/corefx
        public static void AddCrlForCertificate(
            X509Certificate2 cert,
            SafeX509StoreHandle store,
            X509RevocationMode revocationMode,
            DateTime verificationTime,
            ref TimeSpan remainingDownloadTime)
        {
            // In Offline mode, accept any cached CRL we have.
            // "CRL is Expired" is a better match for Offline than "Could not find CRL"
            if (revocationMode != X509RevocationMode.Online)
            {
                verificationTime = DateTime.MinValue;
            }

            if (AddCachedCrl(cert, store, verificationTime))
            {
                return;
            }

            // Don't do any work if we're over limit or prohibited from fetching new CRLs
            if (remainingDownloadTime <= TimeSpan.Zero ||
                revocationMode != X509RevocationMode.Online)
            {
                return;
            }

            DownloadAndAddCrl(cert, store, ref remainingDownloadTime);
        }
コード例 #42
0
        public bool Verify(string originalString, string hashedString, System.Security.Cryptography.X509Certificates.X509Certificate2 certificate)
        {
            //Precondition check...
            if (certificate == null || string.IsNullOrEmpty(originalString) || string.IsNullOrEmpty(hashedString))
            {
                throw new ArgumentNullException(Resources.InValidSigningParams);
            }



            // Get its associated CSP and public key
            RSACryptoServiceProvider csp = (RSACryptoServiceProvider)certificate.PublicKey.Key;

            // Hash the data
            SHA1Managed  sha1     = new SHA1Managed();
            UTF8Encoding encoding = new UTF8Encoding();

            byte[] data = encoding.GetBytes(originalString);
            byte[] hash = sha1.ComputeHash(data);

            byte[] signature = Convert.FromBase64String(hashedString);

            // Verify the signature with the hash
            return(csp.VerifyHash(hash, CryptoConfig.MapNameToOID("SHA1"), signature));
        }
コード例 #43
0
ファイル: Cert.cs プロジェクト: Devancy/Cryptosys.Example
        public static X509Certificate2 GenerateCACertificate(string subjectName, ref AsymmetricKeyParameter CaPrivateKey)
        {
            const int keyStrength = 2048;

            // Generating Random Numbers
            CryptoApiRandomGenerator randomGenerator = new CryptoApiRandomGenerator();
            SecureRandom             random          = new SecureRandom(randomGenerator);

            // The Certificate Generator
            X509V3CertificateGenerator certificateGenerator = new X509V3CertificateGenerator();

            // Serial Number
            BigInteger serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random);

            certificateGenerator.SetSerialNumber(serialNumber);

            // Signature Algorithm
            //const string signatureAlgorithm = "SHA256WithRSA";
            //certificateGenerator.SetSignatureAlgorithm(signatureAlgorithm);

            // Issuer and Subject Name
            X509Name subjectDN = new X509Name(subjectName);
            X509Name issuerDN  = subjectDN;

            certificateGenerator.SetIssuerDN(issuerDN);
            certificateGenerator.SetSubjectDN(subjectDN);

            // Valid For
            DateTime notBefore = DateTime.UtcNow.Date;
            DateTime notAfter  = notBefore.AddYears(2);

            certificateGenerator.SetNotBefore(notBefore);
            certificateGenerator.SetNotAfter(notAfter);

            // Subject Public Key
            AsymmetricCipherKeyPair subjectKeyPair;
            KeyGenerationParameters keyGenerationParameters = new KeyGenerationParameters(random, keyStrength);
            RsaKeyPairGenerator     keyPairGenerator        = new RsaKeyPairGenerator();

            keyPairGenerator.Init(keyGenerationParameters);
            subjectKeyPair = keyPairGenerator.GenerateKeyPair();

            certificateGenerator.SetPublicKey(subjectKeyPair.Public);

            // Generating the Certificate
            AsymmetricCipherKeyPair issuerKeyPair = subjectKeyPair;

            // selfsign certificate
            //Org.BouncyCastle.X509.X509Certificate certificate = certificateGenerator.Generate(issuerKeyPair.Private, random);
            ISignatureFactory signatureFactory = new Asn1SignatureFactory("SHA512WITHRSA", issuerKeyPair.Private, random);

            Org.BouncyCastle.X509.X509Certificate certificate = certificateGenerator.Generate(signatureFactory);
            X509Certificate2 x509 = new System.Security.Cryptography.X509Certificates.X509Certificate2(certificate.GetEncoded());

            CaPrivateKey = issuerKeyPair.Private;

            return(x509);
            //return issuerKeyPair.Private;
        }
コード例 #44
0
ファイル: WssOptions.cs プロジェクト: jollitycn/JGNet
 public WssOptions(System.Security.Cryptography.X509Certificates.X509Certificate2 cer, System.Security.Authentication.SslProtocols pro, bool onlyWss)
 {
     this.sslProtocols_0     = System.Security.Authentication.SslProtocols.Default;
     this.bool_0             = false;
     this.x509Certificate2_0 = cer;
     this.sslProtocols_0     = pro;
     this.bool_0             = onlyWss;
 }
コード例 #45
0
        /// <summary>
        /// Create a new file with the certificate
        /// </summary>
        /// <param name="certificate">The certificate</param>
        /// <param name="outputFileName">The output file name</param>
        private static void WriteCertificate(X509Certificate2 certificate, string outputFileName)
        {
            // This password is the one attached to the PFX file. Use 'null' for no password.
            const string password = "******";
            var          bytes    = certificate.Export(X509ContentType.Pfx, password);

            File.WriteAllBytes(outputFileName, bytes);
        }
コード例 #46
0
        static void AsFrom(SX.X509Certificate2 certificate, out X509Certificate one, out AsymmetricKeyParameter tow)
        {
            one = DotNetUtilities.FromX509Certificate(certificate);



            tow = DotNetUtilities.GetRsaKeyPair(SX.RSACertificateExtensions.GetRSAPrivateKey(certificate)).Private;
        }
コード例 #47
0
        public void MakeItSo(string certificateName, List <string> subjectAlternateNames, string certificateFileName, string privateKeyFilePassword, string rootsigningCertFileName)
        {
            string issuerCnName = string.Format("CN={0}", DefaultIssuer);
            AsymmetricKeyParameter caPrivKey = GenerateCACertificate(issuerCnName, privateKeyFilePassword, rootsigningCertFileName);

            System.Security.Cryptography.X509Certificates.X509Certificate2 cert = GenerateSelfSignedCertificate(certificateName, subjectAlternateNames, certificateFileName, privateKeyFilePassword, issuerCnName, caPrivKey);
            AddCertToStore(cert, System.Security.Cryptography.X509Certificates.StoreName.My, System.Security.Cryptography.X509Certificates.StoreLocation.LocalMachine);
        }
コード例 #48
0
ファイル: HttpsClientStream.cs プロジェクト: raj581/Marvin
        internal override bool RaiseServerCertificateValidation(X509Certificate certificate, int[] certificateErrors)
        {
            bool failed = (certificateErrors.Length > 0);

            // only one problem can be reported by this interface
            _status = ((failed) ? certificateErrors [0] : 0);

#if NET_2_0
#pragma warning disable 618
#endif
            if (ServicePointManager.CertificatePolicy != null)
            {
                ServicePoint sp  = _request.ServicePoint;
                bool         res = ServicePointManager.CertificatePolicy.CheckValidationResult(sp, certificate, _request, _status);
                if (!res)
                {
                    return(false);
                }
                failed = true;
            }
#if NET_2_0
#pragma warning restore 618
#endif
#if NET_2_0
            if (HaveRemoteValidation2Callback)
            {
                return(failed);                // The validation already tried the 2.0 callback
            }
            SNS.RemoteCertificateValidationCallback cb = ServicePointManager.ServerCertificateValidationCallback;
            if (cb != null)
            {
                SNS.SslPolicyErrors ssl_errors = 0;
                foreach (int i in certificateErrors)
                {
                    if (i == (int)-2146762490)                     // TODO: is this what happens when the purpose is wrong?
                    {
                        ssl_errors |= SNS.SslPolicyErrors.RemoteCertificateNotAvailable;
                    }
                    else if (i == (int)-2146762481)
                    {
                        ssl_errors |= SNS.SslPolicyErrors.RemoteCertificateNameMismatch;
                    }
                    else
                    {
                        ssl_errors |= SNS.SslPolicyErrors.RemoteCertificateChainErrors;
                    }
                }
                SNCX.X509Certificate2 cert2 = new SNCX.X509Certificate2(certificate.GetRawCertData());
                SNCX.X509Chain        chain = new SNCX.X509Chain();
                if (!chain.Build(cert2))
                {
                    ssl_errors |= SNS.SslPolicyErrors.RemoteCertificateChainErrors;
                }
                return(cb(_request, cert2, chain, ssl_errors));
            }
#endif
            return(failed);
        }
コード例 #49
0
        /// <summary>
        /// 获取证书对象
        /// </summary>
        /// <param name="certFilePath">证书路径</param>
        /// <returns></returns>
        public static X509Certificate2 GetCertObject(string certFilePath)
        {
            System.Security.Cryptography.X509Certificates.X509Certificate2 x509 =
                new System.Security.Cryptography.X509Certificates.X509Certificate2(certFilePath,
                                                                                   PapdHelper.DEFAULT_PFX_PASSWORD,
                                                                                   X509KeyStorageFlags.Exportable);

            return(x509);
        }
コード例 #50
0
        private void StoreCertificate(X509Name name, MSX509.X509Certificate2 certificate, MSX509.StoreName storeName)
        {
            MSX509.X509Store store = new MSX509.X509Store(storeName, store_);
            store.Open(MSX509.OpenFlags.ReadWrite);
            store.Add(certificate);
            store.Close();

            certificates_[name] = certificate;
        }
コード例 #51
0
 public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
 {
     System.Security.Cryptography.X509Certificates.X509Certificate2 cert = value as System.Security.Cryptography.X509Certificates.X509Certificate2;
     if ("ca".Equals(parameter))
     {
         return(cert?.IssuerInfo());
     }
     return(cert?.SubjectInfo());
 }
コード例 #52
0
        internal static string GeneratePem(X509Certificate2 cert)
        {
            string base64Cert = Convert.ToBase64String(cert.Export(X509ContentType.Cert));
            var    section    = "CERTIFICATE";
            var    header     = String.Format("-----BEGIN {0}-----", section);
            var    footer     = String.Format("-----END {0}-----", section);

            return(header + "\n" + base64Cert + "\n" + footer);
        }
コード例 #53
0
        public static X509Certificate2 Consultar(string valor, StoreName storeName, StoreLocation storeLocation,
                                                 TipoConsultaCertificado tpConsultaTipoCertificado)
        {
            System.Security.Cryptography.X509Certificates.X509Certificate2 _X509Cert = new System.Security.Cryptography.X509Certificates.X509Certificate2();

            try
            {
                X509Store store = new X509Store(storeName, storeLocation);
                store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
                X509Certificate2Collection collection  = (X509Certificate2Collection)store.Certificates;
                X509Certificate2Collection collection1 = (X509Certificate2Collection)collection.Find(X509FindType.FindByTimeValid, DateTime.Now, false);
                X509Certificate2Collection collection2 = (X509Certificate2Collection)collection.Find(X509FindType.FindByKeyUsage, X509KeyUsageFlags.DigitalSignature, false);
                if (valor == "")
                {
                    //Exibe uma lista de certificado existentes na maquina do usuário
                    X509Certificate2Collection scollection =
                        X509Certificate2UI.SelectFromCollection(collection2, "Certificado(s) Digital(is) disponível(is)", "Selecione o Certificado Digital para uso no aplicativo", X509SelectionFlag.SingleSelection);
                    if (scollection.Count > 0)
                    {
                        return(scollection[0]);
                    }
                }
                else
                {
                    //Consulta com base no tipo de solicitação
                    X509Certificate2Collection scollection = null;
                    switch (tpConsultaTipoCertificado)
                    {
                    case TipoConsultaCertificado.PorNome:
                        scollection = (X509Certificate2Collection)collection2
                                      .Find(X509FindType.FindBySubjectDistinguishedName, valor, false);
                        break;

                    case TipoConsultaCertificado.PorNroSerie:
                        scollection = (X509Certificate2Collection)collection2
                                      .Find(X509FindType.FindBySerialNumber, valor, true);
                        break;
                    }
                    if (scollection != null)
                    {
                        if (scollection.Count > 0)
                        {
                            return(scollection[0]);
                        }
                    }
                }
                store.Close();
            }
            catch (System.Exception ex)
            {
                string msg = string.Format("Erro ao consultar o cetificado digital:{0}", ex.Message);
                throw new Exception(msg);
            }


            return(null);
        }
コード例 #54
0
 public static bool Load()
 {
     try
     {
         Certificate = new System.Security.Cryptography.X509Certificates.X509Certificate2(Config.AppSettings["CertFile"].Value, password);
     }
     catch (Exception) { }
     return(ContainsCertificate);
 }
コード例 #55
0
ファイル: PdfSign.cs プロジェクト: angelmontess/InfoPdf
        public static bool SignHashed(string Source, string Target, SysX509.X509Certificate2 Certificate, string Reason, string Location, bool AddVisibleSign, bool AddTimeStamp, string strTSA)
        {
            PdfReader  objReader  = null;
            PdfStamper objStamper = null;

            try
            {
                X509CertificateParser objCP    = new Org.BouncyCastle.X509.X509CertificateParser();
                X509Certificate[]     objChain = new X509Certificate[] { objCP.ReadCertificate(Certificate.RawData) };

                IList <ICrlClient> crlList = new List <ICrlClient>();
                crlList.Add(new CrlClientOnline(objChain));

                objReader  = new PdfReader(Source);
                objStamper = PdfStamper.CreateSignature(objReader, new FileStream(Target, FileMode.Create), '\0', null, true);

                // Creamos la apariencia
                PdfSignatureAppearance signatureAppearance = objStamper.SignatureAppearance;
                signatureAppearance.Reason = "Inforegistro, S.L.";
                //signatureAppearance.Location = Location;

                // Custom signature appearance text
                var font = FontFactory.GetFont("Times New Roman", 11, iTextSharp.text.Font.BOLDITALIC, BaseColor.DARK_GRAY);
                signatureAppearance.Layer2Font = font;
                signatureAppearance.Layer2Text = "Firmado digitalmente por \r\nInforegistro, S.L.\r\nFecha  " + DateTime.Now.ToShortDateString();
                var rectangle = new Rectangle(350, 30, 500, 120);

                // Si está la firma visible:
                if (AddVisibleSign)
                {
                    signatureAppearance.SetVisibleSignature(rectangle, 2, "Inforegistro");
                }

                ITSAClient  tsaClient  = null;
                IOcspClient ocspClient = null;

                // Creating the signature
                IExternalSignature externalSignature = new X509Certificate2Signature(Certificate, "SHA-1");
                MakeSignature.SignDetached(signatureAppearance, externalSignature, objChain, crlList, ocspClient, tsaClient, 0, CryptoStandard.CMS);
                return(File.Exists(Target));
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (objReader != null)
                {
                    objReader.Close();
                }
                if (objStamper != null)
                {
                    objStamper.Close();
                }
            }
        }
コード例 #56
0
ファイル: Program.cs プロジェクト: HubCrike/JMS
        static void Main(string[] args)
        {
            while (true)
            {
                try
                {
                    NetClient client = new NetClient("127.0.0.1", 8911);
                    client.Dispose();
                    break;
                }
                catch (Exception)
                {
                    Thread.Sleep(100);
                }
            }

            var gatewaycert = new System.Security.Cryptography.X509Certificates.X509Certificate2("../../../../pfx/client.pfx", "123456");

            ServiceCollection services = new ServiceCollection();

            var gateways = new NetAddress[] {
                new NetAddress {
                    Address = "localhost",
                    Port    = 8911
                }
            };
            var msp = new MicroServiceHost(services);


            var builder = new ConfigurationBuilder();

            builder.AddJsonFile("appsettings.json", optional: true, reloadOnChange: false);
            var configuration = builder.Build();

            //services.UseJmsTokenAuthentication(AuthorizationContentType.String, "127.0.0.1", 9911,"auth");
            services.AddLogging(loggingBuilder =>
            {
                loggingBuilder.AddConfiguration(configuration.GetSection("Logging"));
                loggingBuilder.AddConsole(); // 将日志输出到控制台
            });
            services.AddSingleton <IConfiguration>(configuration);



            msp.Register <Controller1>("Controller1");
            msp.Register <Controller2>("Service2");
            msp.RegisterScheduleTask <AutoRun1>();
            msp.ServiceProviderBuilded += Msp_ServiceProviderBuilded;
            msp.Build(8912, gateways)
            .UseSSL(c =>
            {     //配置ssl
                c.GatewayClientCertificate = gatewaycert;
                c.ServerCertificate        = new X509Certificate2("../../../../pfx/service_server.pfx", "123456");
            })
            .Run();
        }
コード例 #57
0
        static void Main(string[] args)
        {
            var success = false;

            // read the private certificate file to sign the request to exchange token for ticket

            var certificate = File.ReadAllText(AppContext.BaseDirectory + "ServiceConsoleCert.xml");

            // sign the token

            var signedToken = Sign(certificate, Constants.SystemUserToken);

            // exchange the token for a system user ticket

            var response = Authenticate(Constants.ApplicationToken, Constants.ContextIdentifier, signedToken);

            if (response.IsSuccessful)
            {
                var superOfficeCertificate = new System.Security.Cryptography.X509Certificates.X509Certificate2(
                    AppContext.BaseDirectory + "SuperOfficeFederatedLogin.crt");

                // validate JWT token from SuperOffice

                var validToken = ValidateAndDecode(response.Token, new[] { new X509SecurityKey(superOfficeCertificate) });

                // validate response...
                // extract claims from the token
                var claims = validToken.Claims.Select(c => new Claim(c.Type, c.Value, ClaimValueTypes.String)).ToArray();

                // get the system user ticket (which is used in Http request header "SOTicket ${sysUserTicketValue}"

                var systemUserTicket = claims.FirstOrDefault(c => c.Type.Contains("ticket")).Value;

                // Online base REST endpoint url

                var webapi_url = claims.FirstOrDefault(c => c.Type.Contains("webapi")).Value;

                /* User systemUserTicket to create REST calls to the webapi_url...
                 * GET /Cust26759/api/v1/MDOList/category?flat=True HTTP/1.1
                 *  Host: sod.superoffice.com
                 *  accept: application/json
                 *  authorization: SOTICKET 7T:MAA3AGYAMQBlAGQAZAAxAGQAZQAwADgAYgAxAGEAYwBkADYAOAA0ADcAMQA2ADkAOQBhADQAZgBiADMAOQAyADsAMgAwADgANwAzADEANQAwADQAMwA7AEMAdQBzAHQAMgA2ADcANQA5AA==
                 *  accept-language: en
                 *  SO-AppToken: f2398a3a7wer3759d4b220e9a9c94321
                 */
                success = true;

                Console.WriteLine($"Ticket: {systemUserTicket}");
                Console.WriteLine($"WebAPI URL: {webapi_url}");
            }

            Console.WriteLine(success ? "Success!" : "Failed!");
            Console.WriteLine("");
            Console.WriteLine("Press any key to quit...");
            Console.ReadLine();
        }
コード例 #58
0
ファイル: RSA.cs プロジェクト: smilesand/Mottled
        public static AsymmetricKeyParameter GenerateCACertificate(string subjectName, int keyStrength = 2048)
        {
            // Generating Random Numbers
            var randomGenerator = new CryptoApiRandomGenerator();
            var random          = new SecureRandom(randomGenerator);

            // The Certificate Generator
            var certificateGenerator = new X509V3CertificateGenerator();

            // Serial Number
            var serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random);

            certificateGenerator.SetSerialNumber(serialNumber);

            // Signature Algorithm
            const string signatureAlgorithm = "SHA256WithRSA";

            certificateGenerator.SetSignatureAlgorithm(signatureAlgorithm);

            // Issuer and Subject Name
            var subjectDN = new X509Name(subjectName);
            var issuerDN  = subjectDN;

            certificateGenerator.SetIssuerDN(issuerDN);
            certificateGenerator.SetSubjectDN(subjectDN);

            // Valid For
            var notBefore = DateTime.UtcNow.Date;
            var notAfter  = notBefore.AddYears(2);

            certificateGenerator.SetNotBefore(notBefore);
            certificateGenerator.SetNotAfter(notAfter);

            // Subject Public Key
            AsymmetricCipherKeyPair subjectKeyPair;
            var keyGenerationParameters = new KeyGenerationParameters(random, keyStrength);
            var keyPairGenerator        = new RsaKeyPairGenerator();

            keyPairGenerator.Init(keyGenerationParameters);
            subjectKeyPair = keyPairGenerator.GenerateKeyPair();

            certificateGenerator.SetPublicKey(subjectKeyPair.Public);

            // Generating the Certificate
            var issuerKeyPair = subjectKeyPair;

            // selfsign certificate
            var certificate = certificateGenerator.Generate(issuerKeyPair.Private, random);
            var x509        = new System.Security.Cryptography.X509Certificates.X509Certificate2(certificate.GetEncoded());


            // Add CA certificate to Root store
            addCertToStore(x509, StoreName.Root, StoreLocation.CurrentUser);

            return(issuerKeyPair.Private);
        }
コード例 #59
0
        // Helper methods

        private static void IndexFolder(string folderName, StringBuilder sb, bool noProgress, bool verify)
        {
            // Process all file in folder
            foreach (var fileName in Directory.GetFiles(folderName))
            {
                if (!_certExts.Contains(Path.GetExtension(fileName).ToLowerInvariant()))
                {
                    continue;
                }

                // Get basic cert properties
                var cert            = new System.Security.Cryptography.X509Certificates.X509Certificate2(fileName);
                var serialNumberHex = "0x" + cert.GetSerialNumberString();
                var serialNumberDec = uint.Parse(cert.GetSerialNumberString(), System.Globalization.NumberStyles.HexNumber);
                var email           = cert.GetNameInfo(System.Security.Cryptography.X509Certificates.X509NameType.EmailName, false);
                var domain          = email.Substring(email.IndexOf('@') + 1);
                var name            = cert.GetNameInfo(System.Security.Cryptography.X509Certificates.X509NameType.SimpleName, false);
                if (!noProgress)
                {
                    Console.Write($"0x{serialNumberHex,-8} {email,-40} {name,-30} ");
                }

                // Verify certificate
                var status = "Unknown";
                if (verify)
                {
                    var certValid = ValidateCertificate(cert);
                    status = certValid ? "OK" : "Revoked";
                }
                if (!noProgress)
                {
                    Console.WriteLine(status);
                }

                // Add line to index
                sb.AppendLine(string.Join(CSV_SEPARATOR,
                                          serialNumberHex,
                                          serialNumberDec,
                                          cert.GetCertHashString(),
                                          cert.NotBefore.ToString("yyyy-MM-dd"),
                                          cert.NotAfter.ToString("yyyy-MM-dd"),
                                          cert.PublicKey.Key.KeySize,
                                          status,
                                          domain,
                                          name,
                                          email,
                                          cert.Issuer,
                                          cert.Subject));
            }

            // Crafl subfolders
            foreach (var subFolderName in Directory.GetDirectories(folderName))
            {
                IndexFolder(subFolderName, sb, noProgress, verify);
            }
        }
コード例 #60
0
            private static bool CheckCertificateUsage(System.Security.Cryptography.X509Certificates.X509Certificate2 cert)
            {
                bool result;

                try
                {
                    if (cert.Version < 3)
                    {
                        result = true;
                    }
                    else
                    {
                        System.Security.Cryptography.X509Certificates.X509KeyUsageExtension         x509KeyUsageExtension         = (System.Security.Cryptography.X509Certificates.X509KeyUsageExtension)cert.Extensions["2.5.29.15"];
                        System.Security.Cryptography.X509Certificates.X509EnhancedKeyUsageExtension x509EnhancedKeyUsageExtension = (System.Security.Cryptography.X509Certificates.X509EnhancedKeyUsageExtension)cert.Extensions["2.5.29.37"];
                        if (x509KeyUsageExtension != null && x509EnhancedKeyUsageExtension != null)
                        {
                            if ((x509KeyUsageExtension.KeyUsages & ServicePointManager.ChainValidationHelper.s_flags) == System.Security.Cryptography.X509Certificates.X509KeyUsageFlags.None)
                            {
                                result = false;
                            }
                            else
                            {
                                result = (x509EnhancedKeyUsageExtension.EnhancedKeyUsages["1.3.6.1.5.5.7.3.1"] != null || x509EnhancedKeyUsageExtension.EnhancedKeyUsages["2.16.840.1.113730.4.1"] != null);
                            }
                        }
                        else if (x509KeyUsageExtension != null)
                        {
                            result = ((x509KeyUsageExtension.KeyUsages & ServicePointManager.ChainValidationHelper.s_flags) != System.Security.Cryptography.X509Certificates.X509KeyUsageFlags.None);
                        }
                        else if (x509EnhancedKeyUsageExtension != null)
                        {
                            result = (x509EnhancedKeyUsageExtension.EnhancedKeyUsages["1.3.6.1.5.5.7.3.1"] != null || x509EnhancedKeyUsageExtension.EnhancedKeyUsages["2.16.840.1.113730.4.1"] != null);
                        }
                        else
                        {
                            System.Security.Cryptography.X509Certificates.X509Extension x509Extension = cert.Extensions["2.16.840.1.113730.1.1"];
                            if (x509Extension != null)
                            {
                                string text = x509Extension.NetscapeCertType(false);
                                result = (text.IndexOf("SSL Server Authentication") != -1);
                            }
                            else
                            {
                                result = true;
                            }
                        }
                    }
                }
                catch (Exception arg)
                {
                    Console.Error.WriteLine("ERROR processing certificate: {0}", arg);
                    Console.Error.WriteLine("Please, report this problem to the Mono team");
                    result = false;
                }
                return(result);
            }