• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C# X509Certificates.X509Certificate2类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中System.Security.Cryptography.X509Certificates.X509Certificate2的典型用法代码示例。如果您正苦于以下问题:C# X509Certificate2类的具体用法?C# X509Certificate2怎么用?C# X509Certificate2使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



X509Certificate2类属于System.Security.Cryptography.X509Certificates命名空间,在下文中一共展示了X509Certificate2类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: UnbindInternal

        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;
        }
开发者ID:hallatore,项目名称:ITfoxtec.SAML2,代码行数:25,代码来源:Saml2Binding.cs


示例2: Client

        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;
        }
开发者ID:Team7-SoftEng,项目名称:GateofGabethulu-launcher,代码行数:27,代码来源:Client.cs


示例3: X509ChainElement

		// 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;
		}
开发者ID:nlhepler,项目名称:mono,代码行数:10,代码来源:X509ChainElement.cs


示例4: GetSecurityTokenHandler

        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;
        }
开发者ID:RickVanRousselt,项目名称:PnP-Store,代码行数:28,代码来源:IdentityToken.cs


示例5: assinarEmLote

        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;
        }
开发者ID:alexandresoliveira,项目名称:NotaFiscalEletronica,代码行数:25,代码来源:AssinarRPS.cs


示例6: SignatureProcessor

 public SignatureProcessor(X509Certificate2 certificate, ProtocolSettings discoveryInfo)
 {
     this.Certificate = certificate;
     this.discoveryInfo = discoveryInfo;
     this.SHA1SignatureName = ProtocolStrings.SignatureAlgorithmSHA1Uri;
     this.references = new List<ReferenceEntry>();
 }
开发者ID:tian1ll1,项目名称:WPF_Examples,代码行数:7,代码来源:SignatureProcessor.cs


示例7: Encrypt

        /// <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; 
        }
开发者ID:OPCFoundation,项目名称:UA-.NETStandardLibrary,代码行数:30,代码来源:UserIdentityToken.cs


示例8: Decrypt

        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);
        }
开发者ID:RyanHauert,项目名称:fubumvc,代码行数:27,代码来源:AssertionXmlDecryptor.cs


示例9: AzureCurrentDeployment

 public AzureCurrentDeployment(string deploymentPrivateId, string subscriptionId, X509Certificate2 certificate, IProvisioningObserver observer = null)
 {
     _subscriptionId = subscriptionId;
     _certificate = certificate;
     _deploymentPrivateId = deploymentPrivateId;
     _observer = observer;
 }
开发者ID:TeamKnowledge,项目名称:lokad-cloud-provisioning,代码行数:7,代码来源:AzureCurrentDeployment.cs


示例10: BuildService

        /// <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;
        }
开发者ID:RRedFalcon,项目名称:GSD,代码行数:36,代码来源:gsd.library.GoogleAPI.cs


示例11: ConfigureServices

        // 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);



        }
开发者ID:Charmatzis,项目名称:IT4GOV,代码行数:32,代码来源:Startup.cs


示例12: CreateStorageAcc

 /// <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"];
 }
开发者ID:nazik,项目名称:inst4wa,代码行数:14,代码来源:ServiceManagementHelpers.cs


示例13: AzureDiscovery

 public AzureDiscovery(string subscriptionId, X509Certificate2 certificate, IProvisioningObserver observer = null)
 {
     _subscriptionId = subscriptionId;
     _certificate = certificate;
     _observer = observer;
     _policies = new RetryPolicies(observer);
 }
开发者ID:TeamKnowledge,项目名称:lokad-cloud-provisioning,代码行数:7,代码来源:AzureDiscovery.cs


示例14: Add

        public int Add(X509Certificate2 certificate)
        {
            if (certificate == null)
                throw new ArgumentNullException("certificate");

            return List.Add(certificate);
        }
开发者ID:johnhhm,项目名称:corefx,代码行数:7,代码来源:X509Certificate2Collection.cs


示例15: DeploymentServerCertificateValidator

    public DeploymentServerCertificateValidator(X509Certificate2 allowedCertificate) {
      if (allowedCertificate == null) {
        throw new ArgumentNullException("allowedCertificate");
      }

      this.allowedCertificate = allowedCertificate;
    }
开发者ID:thunder176,项目名称:HeuristicLab,代码行数:7,代码来源:DeploymentServerCertificateValidator.cs


示例16: ConfigureMiddleware

        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;
        }
开发者ID:eugv86,项目名称:Thinktecture.IdentityServer.v3.Samples,代码行数:29,代码来源:SelfContainedTokenValidationExtensions.cs


示例17: ValidateCertificate

 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);
     }
 }
开发者ID:Scalepoint,项目名称:OAuthJwtAssertionTokenClient,代码行数:25,代码来源:JwtAssertionTokenClient.cs


示例18: GetSubjectKeyIdentifier

        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;
        }
开发者ID:pengweiqhca,项目名称:Security,代码行数:7,代码来源:CertificateSubjectKeyIdentifierValidator.cs


示例19: CreateGatewayManagementChannel

 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();
 }
开发者ID:bueti,项目名称:azure-sdk-tools,代码行数:7,代码来源:GatewayManagementHelper.cs


示例20: AddCrlForCertificate

        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);
        }
开发者ID:nnyamhon,项目名称:corefx,代码行数:28,代码来源:CrlCache.cs



注:本文中的System.Security.Cryptography.X509Certificates.X509Certificate2类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# X509Certificates.X509Certificate2Collection类代码示例发布时间:2022-05-26
下一篇:
C# X509Certificates.X509Certificate类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap