public static bool ValidateCertificates(X509Certificate2 cert) { var pathCA = Directory.GetCurrentDirectory() + "/../../CryptoFiles/rootca.pem"; var caCertificate = new X509CertificateParser().ReadCertificate(File.ReadAllBytes(pathCA)); var pathCRL = Directory.GetCurrentDirectory() + "/../../CryptoFiles/crl/list.pem"; var crl = new X509CrlParser().ReadCrl(File.ReadAllBytes(pathCRL)); var receiverCert = new X509CertificateParser().ReadCertificate(cert.GetRawCertData()); try { receiverCert.Verify(caCertificate.GetPublicKey()); } catch { MessageBox.Show("Receiver's certificate is not signed by CA!"); return(false); } if (crl.IsRevoked(receiverCert)) { MessageBox.Show("Receiver's certificate is revoked!"); return(false); } return(true); }
static void CheckValidityOfResponse(CertID id, BasicOcspResp responseObject, Ca ca) { var inputStream = new MemoryStream(responseObject.GetEncoded()); var asn1Sequence = (Asn1Sequence) new Asn1InputStream(inputStream).ReadObject(); var response = BasicOcspResponse.GetInstance(asn1Sequence); var ocspChain = CreateOcspCertificateChain(ca); if (ocspChain.Length == 0) { throw new OcspException("OCSP certificate chain is invalid"); } var ocesOcspCertificate = OcesCertificateFactory.Instance.Generate(CompleteOcspChain(response, ocspChain)); CheckBasicOcspResp(id, responseObject, ocesOcspCertificate, ca); var signingCertificate = new X509CertificateParser().ReadCertificate(response.Certs[0].GetEncoded()); var issuingCertificate = new X509CertificateParser().ReadCertificate(ocspChain[0].GetRawCertData()); signingCertificate.Verify(issuingCertificate.GetPublicKey()); if (!responseObject.Verify(signingCertificate.GetPublicKey())) { throw new OcspException("Signature is invalid"); } }
/// <summary> /// If the device is not "vendor certified" it will only present the Alias Certificate, which is /// validated in this routine. The essential security checks are: /// 1) Does it have a RIoT extension containing the DeviceID? /// 2) Is the certificate signed by the corresponding private DeviceID? /// 3) Is the DeviceID "authorized." In the simple case, is it exactly the device DeviceID /// indicated by the code that instantiated the TLSServer object. /// </summary> /// <param name="certificate"></param> /// <returns></returns> internal static bool ValidateBareCertificate(X509Certificate2 certificate) { Helpers.Notify($"Device presented a bare certificate"); var deviceInfo = ExtensionDecoder.Decode(certificate); // check we have a good extension if (deviceInfo == null) { Helpers.Notify("Certificate does not have well-formed RIoT extension", true); return(false); } var devIdPubKeyDEREncoded = deviceInfo.EncodedDeviceIDKey; if (devIdPubKeyDEREncoded.Length != 65) { Helpers.Notify("Public key in extension has incorrect length", true); return(false); } // validating the certificate is signed with the public key encoded in the extension. // This is a critical security check. // Note: this uses the Bouncy Castle libraries var bcCert = new X509CertificateParser().ReadCertificate(certificate.GetRawCertData()); X9ECParameters p = NistNamedCurves.GetByName("P-256"); ECDomainParameters parameters = new ECDomainParameters(p.Curve, p.G, p.N, p.H); var pt = parameters.Curve.DecodePoint(deviceInfo.EncodedDeviceIDKey); ECPublicKeyParameters bcPubKey = new ECPublicKeyParameters(pt, parameters); try { bcCert.Verify(bcPubKey); } catch (Exception e) { Helpers.Notify($"Certificate is not signed using key in extension {e.ToString()}", true); return(false); } if (DeviceIDPEMFile != null) { // Is this key one of the keys registered with DRS (this test code only has one.) ECPublicKeyParameters authorizedDevice = (ECPublicKeyParameters)Helpers.ReadPemObject(DeviceIDPEMFile); // todo: there are probably better equality tests than this! bool keyIsRecognized = (authorizedDevice.Q.XCoord.ToString() == bcPubKey.Q.XCoord.ToString()) && (authorizedDevice.Q.YCoord.ToString() == bcPubKey.Q.YCoord.ToString()); if (!keyIsRecognized) { Helpers.Notify($"DeviceID is not known", true); return(false); } return(true); } // this code supports the "FakeDRSServer. Here, any device that connects to us is presumed good return(true); }
private bool VerificaEmisorCertificado(byte[] certificado, byte[] certificadoAC) { Org.BouncyCastle.X509.X509Certificate cer1 = new X509CertificateParser().ReadCertificate(certificado); Org.BouncyCastle.X509.X509Certificate cer2 = new X509CertificateParser().ReadCertificate(certificadoAC); try { cer1.Verify(cer2.GetPublicKey()); return(true); } catch (Exception ee) { //Logger.Error(ee); return(false); } }
static bool IsSelfSigned(X509Certificate2 certificate) { try { var bcCertificate = new X509CertificateParser().ReadCertificate(certificate.RawData); bcCertificate.Verify(bcCertificate.GetPublicKey()); return(true); } catch (InvalidKeyException) { } catch (CertificateException) { } catch (SignatureException) { } return(false); }
private static bool Verify(X509Certificate2 certificate, AsymmetricKeyParameter publicKey) { try { var bcCertificate = new X509CertificateParser().ReadCertificate(certificate.RawData); bcCertificate.Verify(publicKey); return(true); } catch (InvalidKeyException) { //ignore on purpose } catch (CertificateException) { //ignore on purpose } catch (SignatureException) { //ignore on purpose } return(false); }
/// <summary> /// Generate PFX File /// </summary> /// <param name="signedCERFile"></param> /// <param name="privateKeyFile"></param> /// <param name="v"></param> /// <param name="password"></param> private async void GeneratePFXFile(string signedCERFile, string privateKeyFile, string generateCertificateFile, string password, string friendlyName, string signedCACERFile = null) { // Prepare the pkcs12 certificate store Pkcs12Store store = new Pkcs12StoreBuilder().Build(); AsymmetricKeyParameter privateKey = ReadPrivateKey(privateKeyFile); X509CertificateEntry[] chain = null; // Check if CA root public key file exist? If exist read data from file and verify certificate inside signed requested public key file with CA root public key // If Ca root public key file does not exist, certificate inside signed requested public key file CAN NOT be veryfied // Bundle together the private key, signed certificate and CA Org.BouncyCastle.X509.X509Certificate CAX509Cert = null; if (String.IsNullOrEmpty(signedCACERFile)) { chain = new X509CertificateEntry[1]; //chain[0] = certEntry; } else { chain = new X509CertificateEntry[2]; //chain[0] = certEntry; try { // Import the CA certificate X509Certificate2 certCA = new X509Certificate2(signedCACERFile); //then export it like so byte[] p12CA = certCA.Export(X509ContentType.Cert); CAX509Cert = new X509CertificateParser().ReadCertificate(p12CA); X509CertificateEntry certCAEntry = new X509CertificateEntry(CAX509Cert); chain[1] = certCAEntry; } catch (Exception ex) { Brush bckForeground = tbOutputMessageBox.Foreground; tbOutputMessageBox.Foreground = new SolidColorBrush(Colors.Red); tbOutputMessageBox.Text += "Error reading root CA certificate file: " + signedCACERFile + "\n"; tbOutputMessageBox.Foreground = bckForeground; return; } } // Import data from the signed requested certificate file => file with .cer extension (NOT CA root public key file) X509Certificate2 certSigned = new X509Certificate2(signedCERFile); int errorNum = 0; #region check - old // This is .cer public key file and it doesn't have private key => it's OK //bool isHasPrivateKey = certSigned.HasPrivateKey; //if (!isHasPrivateKey) //{ // errorNum++; // Brush bckForeground = tbOutputMessageBox.Foreground; // tbOutputMessageBox.Foreground = new SolidColorBrush(Colors.Red); // tbOutputMessageBox.Text += "Error, certificate file: "+ signedCERFile+" DOES NOT have a private key!!!" + "\n"; // tbOutputMessageBox.Foreground = bckForeground; //} // This is certificate signed with CA root that not yet been imported to Trusted Root Certification Authorities and can't be verified //bool isOK = certSigned.Verify(); //if (!isOK) //{ // errorNum++; // Brush bckForeground = tbOutputMessageBox.Foreground; // tbOutputMessageBox.Foreground = new SolidColorBrush(Colors.Red); // tbOutputMessageBox.Text += "Error, certificate file: " + signedCERFile + " NOT valid!!!" + "\n"; // tbOutputMessageBox.Foreground = bckForeground; //} #endregion //then export it like so byte[] p12 = certSigned.Export(X509ContentType.Cert); Org.BouncyCastle.X509.X509Certificate signedX509Cert = new X509CertificateParser().ReadCertificate(p12); if (CAX509Cert != null) { try { signedX509Cert.Verify(CAX509Cert.GetPublicKey()); } catch (Exception ex) { errorNum++; Brush bckForeground = tbOutputMessageBox.Foreground; tbOutputMessageBox.Foreground = new SolidColorBrush(Colors.Red); tbOutputMessageBox.Text += "Error certificate file: " + signedCERFile + " Verification error: " + ex.GetHashCode().ToString() + " " + ex.Message + "\n"; tbOutputMessageBox.Foreground = bckForeground; } } else { Brush bckForeground = tbOutputMessageBox.Foreground; tbOutputMessageBox.Foreground = new SolidColorBrush(Colors.Yellow); tbOutputMessageBox.Text += "Certificate file: " + signedCERFile + " CAN NOT be verified, because CA root public key file not provided" + "\n"; tbOutputMessageBox.Foreground = bckForeground; } if (errorNum > 0) { return; } X509CertificateEntry certEntry = new X509CertificateEntry(signedX509Cert); chain[0] = certEntry; store.SetKeyEntry(signedX509Cert.SubjectDN.ToString() + "_key", new AsymmetricKeyEntry(privateKey), chain); // Add the certificate. X509CertificateEntry certificateEntry = new X509CertificateEntry(signedX509Cert); store.SetCertificateEntry(friendlyName, certificateEntry); // Add the private key. store.SetKeyEntry(friendlyName, new AsymmetricKeyEntry(privateKey), new[] { certificateEntry }); try { using (var filestream = new FileStream(generateCertificateFile, FileMode.Create, FileAccess.ReadWrite)) { store.Save(filestream, password.ToCharArray(), new SecureRandom()); } if (chain.Length > 1) { tbOutputMessageBox.Text += "Certificate file with private key: " + generateCertificateFile + " and CA public key sucessfully generated." + "\n"; } else { tbOutputMessageBox.Text += "Certificate file with private key: " + generateCertificateFile + " sucessfully generated." + "\n"; } } catch (Exception ex) { Brush bckForeground = tbOutputMessageBox.Foreground; tbOutputMessageBox.Foreground = new SolidColorBrush(Colors.Red); if (chain.Length > 1) { tbOutputMessageBox.Text += "Error, certificate file with private key: " + generateCertificateFile + " and CA public key DOES NOT sucessfully generated." + "\n"; } else { tbOutputMessageBox.Text += "Certificate file with private key: " + generateCertificateFile + " DOES NOT sucessfully generated." + "\n"; } tbOutputMessageBox.Foreground = bckForeground; var metroWindow = (Application.Current.MainWindow as MetroWindow); await metroWindow.ShowMessageAsync("Info Warning", "ERROR creating certificate file with private key file (.pfx)" + "\n" + "Error: " + ex.Source + " " + ex.Message, MessageDialogStyle.Affirmative); return; } }
/// <summary> /// Generate PFX File /// </summary> /// <param name="signedCERFile"></param> /// <param name="privateKeyFile"></param> /// <param name="v"></param> /// <param name="password"></param> private async void GeneratePFXFile( string signedCERFile, string privateKeyFile, string generateCertificateFile, string password, string friendlyName, string signedMasterCACERFile = null, string signedIntermediateCACERFile = null, string signedIssuerCACERFile = null, string passwordPrivateKey = null) { createPFX.IsEnabled = false; progressring.Visibility = Visibility.Visible; await System.Threading.Tasks.TaskEx.Delay(1000); // Prepare the pkcs12 certificate store Pkcs12Store store = new Pkcs12StoreBuilder().Build(); AsymmetricKeyParameter privateKey = ReadPrivateKey(privateKeyFile, passwordPrivateKey); X509CertificateEntry[] chain = null; int certChainLength = 1; tbOutputMessageBox.Text = ""; // Check if CA root public key file exist? If exist read data from file and verify certificate inside signed requested public key file with CA root public key // If Ca root public key file does not exist, certificate inside signed requested public key file CAN NOT be veryfied // Bundle together the private key, signed certificate and CA Org.BouncyCastle.X509.X509Certificate masterCAX509Cert = null; Org.BouncyCastle.X509.X509Certificate intermediateCAX509Cert = null; Org.BouncyCastle.X509.X509Certificate issuerCAX509Cert = null; if (!String.IsNullOrEmpty(signedMasterCACERFile)) { certChainLength++; } if (!String.IsNullOrEmpty(signedIntermediateCACERFile)) { certChainLength++; } if (!String.IsNullOrEmpty(signedIssuerCACERFile)) { certChainLength++; } chain = new X509CertificateEntry[certChainLength]; if (!String.IsNullOrEmpty(signedMasterCACERFile)) { try { await System.Threading.Tasks.TaskEx.Delay(1000); // Import the CA certificate X509Certificate2 certMasterCA = new X509Certificate2(signedMasterCACERFile); //then export it like so byte[] p12MasterCA = certMasterCA.Export(X509ContentType.Cert); masterCAX509Cert = new X509CertificateParser().ReadCertificate(p12MasterCA); X509CertificateEntry certMasterCAEntry = new X509CertificateEntry(masterCAX509Cert); chain[certChainLength - 1] = certMasterCAEntry; certChainLength--; } catch (Exception ex) { progressring.Visibility = Visibility.Hidden; createPFX.IsEnabled = true; tbOutputMessageBox.Inlines.Add(new Run { Text = "Error reading Master CA certificate file: " + signedMasterCACERFile + "\n", Foreground = System.Windows.Media.Brushes.Red }); return; } } if (!String.IsNullOrEmpty(signedIntermediateCACERFile)) { try { await System.Threading.Tasks.TaskEx.Delay(1000); // Import the CA certificate X509Certificate2 certIntermediateCA = new X509Certificate2(signedIntermediateCACERFile); //then export it like so byte[] p12IntermediateCA = certIntermediateCA.Export(X509ContentType.Cert); intermediateCAX509Cert = new X509CertificateParser().ReadCertificate(p12IntermediateCA); X509CertificateEntry certIntermediateCAEntry = new X509CertificateEntry(intermediateCAX509Cert); chain[certChainLength - 1] = certIntermediateCAEntry; certChainLength--; } catch (Exception ex) { progressring.Visibility = Visibility.Hidden; createPFX.IsEnabled = true; tbOutputMessageBox.Inlines.Add(new Run { Text = "Error reading Intermediate CA certificate file: " + signedMasterCACERFile + "\n", Foreground = System.Windows.Media.Brushes.Red }); return; } } if (!String.IsNullOrEmpty(signedIssuerCACERFile)) { try { await System.Threading.Tasks.TaskEx.Delay(1000); // Import the CA certificate X509Certificate2 certIssuerCA = new X509Certificate2(signedIssuerCACERFile); //then export it like so byte[] p12IssuerCA = certIssuerCA.Export(X509ContentType.Cert); issuerCAX509Cert = new X509CertificateParser().ReadCertificate(p12IssuerCA); X509CertificateEntry certIntermediateCAEntry = new X509CertificateEntry(issuerCAX509Cert); chain[certChainLength - 1] = certIntermediateCAEntry; certChainLength--; } catch (Exception ex) { progressring.Visibility = Visibility.Hidden; createPFX.IsEnabled = true; tbOutputMessageBox.Inlines.Add(new Run { Text = "Error reading Intermediate CA certificate file: " + signedMasterCACERFile + "\n", Foreground = System.Windows.Media.Brushes.Red }); return; } } // Import data from the signed requested certificate file => file with .cer extension (NOT CA root public key file) X509Certificate2 certSigned = new X509Certificate2(signedCERFile); int errorNum = 0; await System.Threading.Tasks.TaskEx.Delay(1000); //then export it like so byte[] p12 = certSigned.Export(X509ContentType.Cert); Org.BouncyCastle.X509.X509Certificate signedX509Cert = new X509CertificateParser().ReadCertificate(p12); bool isVeryfyChainCer = false; if (!isVeryfyChainCer) { if (issuerCAX509Cert != null) // Issuer { try { await System.Threading.Tasks.TaskEx.Delay(1000); isVeryfyChainCer = true; signedX509Cert.Verify(issuerCAX509Cert.GetPublicKey()); } catch (Exception ex) { errorNum++; tbOutputMessageBox.Inlines.Add(new Run { Text = "Error Issuer certificate file: " + signedCERFile + " Verification error: " + ex.GetHashCode().ToString() + " " + ex.Message + "\n", Foreground = System.Windows.Media.Brushes.Red }); } } } if (!isVeryfyChainCer) { if (intermediateCAX509Cert != null) // Intermediate { try { await System.Threading.Tasks.TaskEx.Delay(1000); isVeryfyChainCer = true; signedX509Cert.Verify(intermediateCAX509Cert.GetPublicKey()); } catch (Exception ex) { errorNum++; tbOutputMessageBox.Inlines.Add(new Run { Text = "Error Intermediate certificate file: " + signedCERFile + " Verification error: " + ex.GetHashCode().ToString() + " " + ex.Message + "\n", Foreground = System.Windows.Media.Brushes.Red }); } } } if (!isVeryfyChainCer) { if (masterCAX509Cert != null) // Mster { try { await System.Threading.Tasks.TaskEx.Delay(1000); isVeryfyChainCer = true; signedX509Cert.Verify(masterCAX509Cert.GetPublicKey()); } catch (Exception ex) { errorNum++; tbOutputMessageBox.Inlines.Add(new Run { Text = "Error Master certificate file: " + signedCERFile + " Verification error: " + ex.GetHashCode().ToString() + " " + ex.Message + "\n", Foreground = System.Windows.Media.Brushes.Red }); } } } if (errorNum > 0) { progressring.Visibility = Visibility.Hidden; createPFX.IsEnabled = true; return; } //--------------------------------------------------------------------------------- X509CertificateEntry certEntry = new X509CertificateEntry(signedX509Cert); await System.Threading.Tasks.TaskEx.Delay(1000); chain[0] = certEntry; store.SetKeyEntry(friendlyName, new AsymmetricKeyEntry(privateKey), chain); try { using (var filestream = new FileStream(generateCertificateFile, FileMode.Create, FileAccess.ReadWrite)) { await System.Threading.Tasks.TaskEx.Delay(1000); store.Save(filestream, password.ToCharArray(), new SecureRandom()); } if (chain.Length > 3) { tbOutputMessageBox.Inlines.Add(new Run { Text = "Certificate file with private key: " + generateCertificateFile + " and Master, Intermediate, Issuer CA public key sucessfully generated." + "\n", Foreground = System.Windows.Media.Brushes.Green }); } else if (chain.Length > 2) { tbOutputMessageBox.Inlines.Add(new Run { Text = "Certificate file with private key: " + generateCertificateFile + " and Master, Intermediate CA public key sucessfully generated." + "\n", Foreground = System.Windows.Media.Brushes.Green }); } else if (chain.Length > 1) { tbOutputMessageBox.Inlines.Add(new Run { Text = "Certificate file with private key: " + generateCertificateFile + " and Master CA public key sucessfully generated." + "\n", Foreground = System.Windows.Media.Brushes.Green }); } else { tbOutputMessageBox.Inlines.Add(new Run { Text = "Certificate file with private key: " + generateCertificateFile + " sucessfully generated." + "\n", Foreground = System.Windows.Media.Brushes.Green }); } } catch (Exception ex) { if (chain.Length > 3) { tbOutputMessageBox.Inlines.Add(new Run { Text = "Error, certificate file with private key: " + generateCertificateFile + " and Master, Intermediate, Issuer CA public key DOES NOT sucessfully generated." + "\n", Foreground = System.Windows.Media.Brushes.Red }); } if (chain.Length > 2) { tbOutputMessageBox.Inlines.Add(new Run { Text = "Error, certificate file with private key: " + generateCertificateFile + " and Master, IntermediateCA public key DOES NOT sucessfully generated." + "\n", Foreground = System.Windows.Media.Brushes.Red }); } if (chain.Length > 1) { tbOutputMessageBox.Inlines.Add(new Run { Text = "Error, certificate file with private key: " + generateCertificateFile + " and Master CA public key DOES NOT sucessfully generated." + "\n", Foreground = System.Windows.Media.Brushes.Red }); } else { tbOutputMessageBox.Inlines.Add(new Run { Text = "Certificate file with private key: " + generateCertificateFile + " DOES NOT sucessfully generated." + "\n", Foreground = System.Windows.Media.Brushes.Red }); } progressring.Visibility = Visibility.Hidden; createPFX.IsEnabled = true; var metroWindow = (Application.Current.MainWindow as MetroWindow); await metroWindow.ShowMessageAsync("Info Warning", "ERROR creating certificate file with private key file (.pfx)" + "\n" + "Error: " + ex.Source + " " + ex.Message, MessageDialogStyle.Affirmative); return; } progressring.Visibility = Visibility.Hidden; createPFX.IsEnabled = true; }