private void ShowCertificateButton_Click(object sender, EventArgs e) { if (!X509Helper.ShowStoredCertificate()) { MessageBox.Show("No certificate was viewed", "Go to browser", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
protected void ThrowIfContextInvalid() { if (!IsValid) { throw X509Helper.GetInvalidContextException(); } }
private void x509BtnLoad_Click(object sender, EventArgs e) { string path = x509PathInput.Text; if (string.IsNullOrEmpty(path) || !File.Exists(path)) { LoadImg = _xlRibbon.LoadImage("error") as Bitmap; ErrorText = "Certificate not found"; return; } try { var x509 = X509Helper.LoadX509FromFile(path, x509PasswordInput.Text); var key = x509.GetECDsaPrivateKey() as ECDsaCng; if (key != null && key.HashAlgorithm == CngAlgorithm.Sha256 && key.KeySize == 256) { SecretariumFunctions.Scp.Set(key); LoadImg = _xlRibbon.LoadImage("success") as Bitmap; ErrorText = " "; } else { LoadImg = _xlRibbon.LoadImage("error") as Bitmap; ErrorText = "Invalid certificate, expecting ECDSA 256"; } } catch (Exception) { LoadImg = _xlRibbon.LoadImage("error") as Bitmap; ErrorText = "Unable to load certificate, incorrect password ?"; } }
public IFluentHpkpOptions PinCertificate(string thumbprint, StoreLocation storeLocation = StoreLocation.LocalMachine, StoreName storeName = StoreName.My) { try { _validator.ValidateThumbprint(thumbprint); } catch (Exception e) { throw new ArgumentException(e.Message, thumbprint); } var helper = new X509Helper(); var cert = helper.GetCertByThumbprint(thumbprint, storeLocation, storeName); var pin = helper.GetSubjectPublicKeyInfoPinValue(cert); cert.Reset(); if (!_pins.Contains(pin)) { _pins.Add(pin); } return(this); }
private static void BuildCAUnit(out AsymmetricKeyParameter caPrivateKey, out X509Certificate caCert) { AsymmetricCipherKeyPair keyPair = AsymmetricAlgorithmHelper.ECDSA.GenerateKeyPair(); caPrivateKey = keyPair.Private; Tuple <X509NameLabel, string>[] names = new Tuple <X509NameLabel, string>[] { new Tuple <X509NameLabel, string>(X509NameLabel.C, "CN"), new Tuple <X509NameLabel, string>(X509NameLabel.CN, "LH.Net.Sockets TEST Root CA") }; X509Name dn = X509Helper.GenerateX509Name(names); Tuple <X509ExtensionLabel, bool, Asn1Encodable>[] exts = new Tuple <X509ExtensionLabel, bool, Asn1Encodable>[] { new Tuple <X509ExtensionLabel, bool, Asn1Encodable>(X509ExtensionLabel.BasicConstraints, true, new BasicConstraints(false)), new Tuple <X509ExtensionLabel, bool, Asn1Encodable>(X509ExtensionLabel.KeyUsage, true, new KeyUsage(KeyUsage.KeyCertSign | KeyUsage.CrlSign)) }; X509Extensions extensions = X509Helper.GenerateX509Extensions(exts); caCert = X509Helper.GenerateIssuerCert("SHA224withECDSA", keyPair, dn, extensions, DateTime.UtcNow.AddDays(-1), 365); _ = PemHelper.KeyToPem(keyPair.Private, PemHelper.DEKAlgorithmNames.RC2_64_CBC, "abc123"); _ = PemHelper.KeyToPem(keyPair.Public); _ = PemHelper.CertToPem(caCert); }
public ActionResult SpidRequest(string idpName) { // Clear user info HttpContext.Session.SetObject <UserInfo>("UserInfo", null); try { // Create the SPID request id string spidAuthnRequestId = Guid.NewGuid().ToString(); // Select the Identity Provider IdentityProvider idp = IdentityProvidersList.GetIdpFromIdPName(idpName); // Retrieve the signing certificate var certificate = X509Helper.GetCertificateFromStore( StoreLocation.LocalMachine, StoreName.My, X509FindType.FindBySubjectName, _configuration["Spid:CertificateName"], validOnly: false); // Create the signed SAML request var spidAuthnRequest = SamlHelper.BuildAuthnPostRequest( uuid: spidAuthnRequestId, destination: idp.EntityID, consumerServiceURL: _configuration["Spid:DomainValue"], securityLevel: 1, certificate: certificate, identityProvider: idp, enviroment: _env.EnvironmentName == "Development" ? 1 : 0); ViewData["data"] = spidAuthnRequest; ViewData["action"] = idp.SingleSignOnServiceUrl; //// Save the IdP label and SPID request id as a cookie //HttpCookie cookie = Request.Cookies.Get(SPID_COOKIE) ?? new HttpCookie(SPID_COOKIE); //cookie.Values["IdPName"] = idpName; //cookie.Values["SpidAuthnRequestId"] = spidAuthnRequestId; //cookie.Expires = DateTime.Now.AddMinutes(20); //Response.Cookies.Add(cookie); // Save the IdPName and SPID request id this.SetCookie("IdPName", idpName, 20); this.SetCookie("SpidAuthnRequestId", spidAuthnRequestId, 20); // Send the request to the Identity Provider return(View("PostData")); } catch (Exception ex) { // TODO: log.Error("Error on HomeController SpidRequest", ex); ViewData["Message"] = "Errore nella preparazione della richiesta di autenticazione da inviare al provider."; ViewData["ErrorMessage"] = ex.Message; return(View("Error")); } }
public IEnumerable <SimpleX509Dto> Certificates() { SetHeaders(); try { return(X509Helper.GetCertificates()); } catch (Exception e) { throw new WebFaultException <Exception>(new Exception(e.Message), HttpStatusCode.InternalServerError); } }
public GitHubClient(GitHubAuth auth) { Auth = auth; _httpClient = X509Helper.GetHttpClientWithCertRevocation(); _httpClient.DefaultRequestHeaders.Add("Accept", "application/vnd.github.v3+json"); _httpClient.DefaultRequestHeaders.Add("User-Agent", auth?.User ?? DefaultUserAgent); if (auth?.AuthToken != null) { _httpClient.DefaultRequestHeaders.Add("Authorization", $"token {auth.AuthToken}"); } }
public static BuildInfo Get( string name, string rawBuildInfoBaseUrl, bool fetchLatestReleaseFile = true) { using (var client = X509Helper.GetHttpClientWithCertRevocation()) { return(GetAsync( client, name, rawBuildInfoBaseUrl, fetchLatestReleaseFile).Result); } }
public ActionResult SpidRequest(string idpName) { try { // Create the SPID request id string spidAuthnRequestId = Guid.NewGuid().ToString(); // Select the Identity Provider IdentityProvider idp = IdentityProvidersList.GetIdpFromIdPName(idpName); // Retrieve the signing certificate var certificate = X509Helper.GetCertificateFromStore( StoreLocation.LocalMachine, StoreName.My, X509FindType.FindBySubjectName, ConfigurationManager.AppSettings["SPID_CERTIFICATE_NAME"], validOnly: false); // Create the signed SAML request var spidAuthnRequest = SamlHelper.BuildAuthnPostRequest( uuid: spidAuthnRequestId, destination: idp.EntityID, consumerServiceURL: ConfigurationManager.AppSettings["SPID_DOMAIN_VALUE"], securityLevel: 1, certificate: certificate, identityProvider: idp, enviroment: ConfigurationManager.AppSettings["ENVIROMENT"] == "dev" ? 1 : 0); ViewData["data"] = spidAuthnRequest; ViewData["action"] = idp.SingleSignOnServiceUrl; // Save the IdP label and SPID request id as a cookie HttpCookie cookie = Request.Cookies.Get(SPID_COOKIE) ?? new HttpCookie(SPID_COOKIE); cookie.Values["IdPName"] = idpName; cookie.Values["SpidAuthnRequestId"] = spidAuthnRequestId; cookie.Expires = DateTime.Now.AddMinutes(20); Response.Cookies.Add(cookie); // Send the request to the Identity Provider return(View("PostData")); } catch (Exception ex) { log.Error("Error on HomeController SpidRequest", ex); ViewData["Message"] = "Errore nella preparazione della richiesta di autenticazione da inviare al provider."; ViewData["ErrorMessage"] = ex.Message; return(View("Error")); } }
private static void BuildServerUnit(out Pkcs10CertificationRequest serverCsr) { AsymmetricCipherKeyPair keyPair = AsymmetricAlgorithmHelper.ECGOST3410.GenerateKeyPair(); Tuple <X509NameLabel, string>[] names = new Tuple <X509NameLabel, string>[] { new Tuple <X509NameLabel, string>(X509NameLabel.C, "CN"), new Tuple <X509NameLabel, string>(X509NameLabel.CN, "LH.Net.Sockets TEST TCP Server") }; X509Name dn = X509Helper.GenerateX509Name(names); Tuple <X509ExtensionLabel, bool, Asn1Encodable>[] exts = new Tuple <X509ExtensionLabel, bool, Asn1Encodable>[] { new Tuple <X509ExtensionLabel, bool, Asn1Encodable>(X509ExtensionLabel.BasicConstraints, true, new BasicConstraints(false)), new Tuple <X509ExtensionLabel, bool, Asn1Encodable>(X509ExtensionLabel.KeyUsage, true, new KeyUsage(KeyUsage.KeyCertSign | KeyUsage.CrlSign)) }; X509Extensions extensions = X509Helper.GenerateX509Extensions(exts); serverCsr = X509Helper.GenerateCsr("GOST3411withECGOST3410", keyPair, dn, extensions); }
public VstsAdapterClient( GitHubAuth auth, string vstsInstanceName, string apiVersionOverride = null) { Auth = auth; VstsInstanceName = vstsInstanceName; _httpClient = X509Helper.GetHttpClientWithCertRevocation(); _httpClient.DefaultRequestHeaders.Add( "Accept", $"application/json;api-version={apiVersionOverride ?? DefaultVstsApiVersion}"); if (auth?.AuthToken != null) { _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue( "Basic", ClientHelpers.ToBase64($":{auth.AuthToken}")); } }
public static SafeSecCertificateHandle FromOtherCertificate(X509CertificateImpl impl) { X509Helper.ThrowIfContextInvalid(impl); var handle = impl.GetNativeAppleCertificate(); if (handle != IntPtr.Zero) { return(new SafeSecCertificateHandle(handle, false)); } using (var data = CFData.FromData(impl.RawData)) { handle = SecCertificateCreateWithData(IntPtr.Zero, data.Handle); if (handle == IntPtr.Zero) { throw new ArgumentException("Not a valid DER-encoded X.509 certificate"); } return(new SafeSecCertificateHandle(handle, true)); } }
public X509Dto CertificateDetails(string hash) { SetHeaders(); try { var x509 = X509Helper.FindCertificate(hash); if (x509 == null) { throw new WebFaultException <NullReferenceException>(new NullReferenceException("Certificate was not found."), HttpStatusCode.NotFound); } return(new X509Dto(x509)); } catch (WebFaultException <NullReferenceException> ) { throw; } catch (Exception e) { throw new WebFaultException <Exception>(new Exception(e.Message), HttpStatusCode.InternalServerError); } }
private static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.ConfigureKestrel(o => { var port = EnvironmentVariableHelper.GetIntEnvironmentVariable("TRADECUBE_REPORTS_HTTPS_PORT"); var certificateInfo = X509Helper.CertificateInfo("TRADECUBE_REPORTS_CERT_NAME", "TRADECUBE_REPORTS_CERT_PASSWORD"); if (X509Helper.IsValidHttpsConfig(port, certificateInfo)) { o.ListenAnyIP(port ?? 0, options => { options.UseHttps(certificateInfo.name, certificateInfo.password); }); } }) .UseStartup <Startup>() .ConfigureLogging(logging => { logging.ClearProviders(); logging.SetMinimumLevel(LogLevel.Trace); }) .UseNLog(); });
public override string ToString(bool full) { ThrowIfContextInvalid(); if (!full || fallback == null) { var summary = GetSubjectSummary(); return(string.Format("[X509Certificate: {0}]", summary)); } string nl = Environment.NewLine; StringBuilder sb = new StringBuilder(); sb.AppendFormat("[Subject]{0} {1}{0}{0}", nl, GetSubjectName(false)); sb.AppendFormat("[Issuer]{0} {1}{0}{0}", nl, GetIssuerName(false)); sb.AppendFormat("[Not Before]{0} {1}{0}{0}", nl, GetValidFrom().ToLocalTime()); sb.AppendFormat("[Not After]{0} {1}{0}{0}", nl, GetValidUntil().ToLocalTime()); sb.AppendFormat("[Thumbprint]{0} {1}{0}", nl, X509Helper.ToHexString(GetCertHash())); sb.Append(nl); return(sb.ToString()); }
public static string SetIdentityFromX509([ExcelArgument("Path to X509 pfx certificate")] string pfxFile, [ExcelArgument("X509 password")] string password) { if (string.IsNullOrEmpty(pfxFile)) { return("Missing pfx file"); } if (string.IsNullOrEmpty(password)) { return("Missing password"); } try { var x509 = X509Helper.LoadX509FromFile(pfxFile, password); if (x509.GetECDsaPrivateKey() is ECDsaCng key && key.HashAlgorithm == CngAlgorithm.Sha256 && key.KeySize == 256) { Scp.Set(key); } else { return("Could not load your identity"); } }
public DiadokAction(ActionPayload payload) { Success = false; InitFields(); Payload = payload; switch (payload.Entity.AttachmentType) { case AttachmentType.XmlTorg12: DocumentName = new DiadocXmlHelper(payload.Entity).GetDiadokTORG12Name(" , "); break; case AttachmentType.Invoice: DocumentName = new DiadocXmlHelper(payload.Entity).GetDiadokInvoiceName(" , "); break; default: DocumentName = payload.Entity.FileName; break; } IsEnabled.Value = true; if (Settings.Value.DebugUseTestSign) { SignerFirstName = "Иван"; SignerSureName = "Иванович"; SignerPatronimic = "Иванов"; SignerINN = Settings.Value.DebugDiadokSignerINN; } else { Cert = Settings.Value.GetCert(Settings.Value.DiadokCert); var certFields = X509Helper.ParseSubject(Cert.Subject); try { var namefp = certFields["G"].Split(' '); SignerFirstName = namefp[0]; SignerSureName = certFields["SN"]; SignerPatronimic = namefp[1]; if (!String.IsNullOrEmpty(Settings.Value.DebugDiadokSignerINN)) { SignerINN = Settings.Value.DebugDiadokSignerINN; } else { if (certFields.Keys.Contains("OID.1.2.643.3.131.1.1")) { SignerINN = certFields["OID.1.2.643.3.131.1.1"]; } if (certFields.Keys.Contains("ИНН")) { SignerINN = certFields["ИНН"]; } if (String.IsNullOrEmpty(SignerINN)) { throw new Exception("Не найдено поле ИНН(OID.1.2.643.3.131.1.1)"); } } SignerINN = SignerINN.Substring(2); } catch (Exception exept) { Log.Error("Ошибка разбора сертификата, G,SN,OID.1.2.643.3.131.1.1", exept); } } }
private static void Demo() { // // CA work // BuildCAUnit(out AsymmetricKeyParameter caPrivateKey, out X509Certificate caCert); // // Subject work // BuildServerUnit(out Pkcs10CertificationRequest serverCsr); BuildClientUnit(out Pkcs10CertificationRequest clientCsr); // // CA work // X509Helper.ExtractCsr(serverCsr, out AsymmetricKeyParameter serverPublicKey, out X509Name serverDN, out X509Extensions serverExtensions); X509Certificate serverCert = X509Helper.GenerateSubjectCert("SHA256WithECDSA", caPrivateKey, caCert, serverPublicKey, serverDN, serverExtensions, DateTime.UtcNow.AddDays(-1), 90); X509Helper.ExtractCsr(clientCsr, out AsymmetricKeyParameter clientPublicKey, out X509Name clientDN, out X509Extensions clientExtensions); // SignatureAlgorithmHelper.TryGetAlgorithm("SHA256WithECDSA", out ISignatureAlgorithm signatureAlgorithm); X509Certificate clientCert = X509Helper.GenerateSubjectCert(signatureAlgorithm, caPrivateKey, caCert, clientPublicKey, clientDN, clientExtensions, DateTime.UtcNow.AddDays(-1), 90); // // // Print // Console.WriteLine("==== CA Cert ====================================================================================="); Console.WriteLine(caCert.ToString()); Console.WriteLine("==== Server Cert ================================================================================="); Console.WriteLine(serverCert.ToString()); Console.WriteLine("==== Client Cert ================================================================================="); Console.WriteLine(clientCert.ToString()); Console.WriteLine(); // // Verify // bool validated; try { serverCert.Verify(caCert.GetPublicKey()); validated = true; } catch { validated = false; } Console.WriteLine("Verify server cert - " + validated); try { clientCert.Verify(caCert.GetPublicKey()); validated = true; } catch { validated = false; } Console.WriteLine("Verify client cert - " + validated); }
public ActionResult LogoutRequest() { string idpName; string subjectNameId; string authnStatementSessionIndex; // Try to get Authentication data from cookie HttpCookie cookie = Request.Cookies[SPID_COOKIE]; if (cookie == null) { // End the session Session["AppUser"] = null; log.Error("Error on HomeController LogoutRequest method: Impossibile recuperare i dati della sessione (cookie scaduto)"); ViewData["Message"] = "Impossibile recuperare i dati della sessione (cookie scaduto)."; return(View("Error")); } idpName = cookie["IdPName"]; subjectNameId = cookie["SubjectNameId"]; authnStatementSessionIndex = cookie["AuthnStatementSessionIndex"]; // Remove the cookie cookie.Values["IdPName"] = string.Empty; cookie.Values["SpidAuthnRequestId"] = string.Empty; cookie.Values["SpidLogoutRequestId"] = string.Empty; cookie.Values["SubjectNameId"] = string.Empty; cookie.Values["AuthnStatementSessionIndex"] = string.Empty; cookie.Expires = DateTime.Now.AddDays(-1); Response.Cookies.Add(cookie); // End the session Session["AppUser"] = null; if (string.IsNullOrWhiteSpace(idpName) || string.IsNullOrWhiteSpace(subjectNameId) || string.IsNullOrWhiteSpace(authnStatementSessionIndex)) { log.Error("Error on HomeController LogoutRequest method: Impossibile recuperare i dati della sessione (il cookie non contiene tutti i dati necessari)"); ViewData["Message"] = "Impossibile recuperare i dati della sessione (il cookie non contiene tutti i dati necessari)."; return(View("Error")); } try { // Create the SPID request id and save it as a cookie string logoutRequestId = Guid.NewGuid().ToString(); // Select the Identity Provider IdentityProvider idp = IdentityProvidersList.GetIdpFromIdPName(idpName); // Retrieve the signing certificate var certificate = X509Helper.GetCertificateFromStore( StoreLocation.LocalMachine, StoreName.My, X509FindType.FindBySubjectName, ConfigurationManager.AppSettings["SPID_CERTIFICATE_NAME"], validOnly: false); // Create the signed SAML logout request var spidLogoutRequest = SamlHelper.BuildLogoutPostRequest( uuid: logoutRequestId, consumerServiceURL: ConfigurationManager.AppSettings["SPID_DOMAIN_VALUE"], certificate: certificate, identityProvider: idp, subjectNameId: subjectNameId, authnStatementSessionIndex: authnStatementSessionIndex); ViewData["data"] = spidLogoutRequest; ViewData["action"] = idp.SingleLogoutServiceUrl; // Save the IdP label and SPID request id as a cookie cookie = new HttpCookie(SPID_COOKIE); cookie.Values["IdPName"] = idpName; cookie.Values["SpidLogoutRequestId"] = logoutRequestId; cookie.Expires = DateTime.Now.AddMinutes(20); Response.Cookies.Add(cookie); // Send the request to the Identity Provider return(View("PostData")); } catch (Exception ex) { log.Error("Error on HomeController SpidRequest", ex); ViewData["Message"] = "Errore nella preparazione della richiesta di logout da inviare al provider."; ViewData["ErrorMessage"] = ex.Message; return(View("Error")); } }
public IFluentHpkpOptions PinCertificate(string thumbprint, StoreLocation storeLocation = StoreLocation.LocalMachine, StoreName storeName = StoreName.My) { try { _validator.ValidateThumbprint(thumbprint); } catch (Exception e) { throw new ArgumentException(e.Message, thumbprint); } var helper = new X509Helper(); var cert = helper.GetCertByThumbprint(thumbprint, storeLocation, storeName); var pin = helper.GetSubjectPublicKeyInfoPinValue(cert); cert.Reset(); if (!_pins.Contains(pin)) { _pins.Add(pin); } return this; }
public ActionResult LogoutRequest() { // Try to get Authentication data from session string idpName = this.GetCookie("IdPName"); string subjectNameId = this.GetCookie("SubjectNameId"); string authnStatementSessionIndex = this.GetCookie("AuthnStatementSessionIndex"); // End the session HttpContext.Session.SetObject <UserInfo>("UserInfo", null); this.RemoveCookie("IdPName"); this.RemoveCookie("SpidAuthnRequestId"); this.RemoveCookie("SpidLogoutRequestId"); this.RemoveCookie("SubjectNameId"); this.RemoveCookie("AuthnStatementSessionIndex"); if (string.IsNullOrWhiteSpace(idpName) || string.IsNullOrWhiteSpace(subjectNameId) || string.IsNullOrWhiteSpace(authnStatementSessionIndex)) { // TODO: log.Error("Error on HomeController LogoutRequest method: Impossibile recuperare i dati della sessione (sessione scaduta)"); ViewData["Message"] = "Impossibile recuperare i dati della sessione (sessione scaduta)."; return(View("Error")); } try { // Create the SPID request id and save it as a cookie string logoutRequestId = Guid.NewGuid().ToString(); // Select the Identity Provider IdentityProvider idp = IdentityProvidersList.GetIdpFromIdPName(idpName); // Retrieve the signing certificate var certificate = X509Helper.GetCertificateFromStore( StoreLocation.LocalMachine, StoreName.My, X509FindType.FindBySubjectName, _configuration["Spid:CertificateName"], validOnly: false); // Create the signed SAML logout request var spidLogoutRequest = SamlHelper.BuildLogoutPostRequest( uuid: logoutRequestId, consumerServiceURL: _configuration["Spid:DomainValue"], certificate: certificate, identityProvider: idp, subjectNameId: subjectNameId, authnStatementSessionIndex: authnStatementSessionIndex); ViewData["data"] = spidLogoutRequest; ViewData["action"] = idp.SingleLogoutServiceUrl; // Save the IdP label and SPID logout request id this.SetCookie("IdPName", idpName, 20); this.SetCookie("SpidLogoutRequestId", logoutRequestId, 20); // Send the request to the Identity Provider return(View("PostData")); } catch (Exception ex) { // TODO: log.Error("Error on HomeController SpidRequest", ex); ViewData["Message"] = "Errore nella preparazione della richiesta di logout da inviare al provider."; ViewData["ErrorMessage"] = ex.Message; return(View("Error")); } }