title: Create and verify x509 certificates in .Net
body: <p>In connection with my enterprise project (intranet only) I came across a question with the verification of certificates using .net <code>System.Security.Cryptography.X509Certificates</code></p>
  
  <p>Step 1: <strong>Creating a root certificate</strong></p>
  
  <p>Use <code>makecert</code> to create a root certificate and install it into the <strong>Trusted Root Certification Authorities</strong></p>
  
  <pre><code>makecert -r -pe -n "CN=Test Labs (CA)" -ss CA -sr CurrentUser -a sha256 -cy authority -sky signature -sv TestLabCA.pvk TestLabCA.cer
  pvk2pfx -pvk TestLabCA.pvk -spc TestLabCA.cer -pfx TestLabCA.pfx
  </code></pre>
  
  <p>Step 2: <strong>Creating a certificate and sign it with the root certificate</strong></p>
  
  <p>Use <code>makecert</code> to create a certificate, sign it with the root certificate and install it to the <strong>Trusted Publishers</strong></p>
  
  <pre><code>makecert -pe -n "CN=Test Labs (SPC)" -a sha256 -cy end -sky signature -ic TestLabCA.cer -iv TestLabCA.pvk -sv TestLabSPC.pvk TestLabSPC.cer
  pvk2pfx -pvk TestLabSPC.pvk -spc TestLabSPC.cer -pfx TestLabSPC.pfx
  </code></pre>
  
  <p>Step 3: <strong>Verify in code</strong></p>
  
  <p>This is the C# code sample to verify the certificates:</p>
  
  <pre><code>X509Certificate2 rootCertificate = new X509Certificate2("TestLabCA.cer");
  X509Certificate2 certificate = new X509Certificate2("TestLabSPC.cer");
  
  // will return true
  Console.WriteLine("{0}, verified = {1}", rootCertificate.GetName(), rootCertificate.Verify());
  
  // will return false
  Console.WriteLine("{0}, verified = {1}", certificate.GetName(), certificate.Verify());
  
  // validate the chain
  var chain = new X509Chain();
  chain.Build(certificate);
  Console.WriteLine("{0}, verified root of chain = {1}", certificate.GetName(), chain.ChainElements[chain.ChainElements.Count-1].Certificate.Verify());
  </code></pre>
  
  <p><strong>Question:</strong></p>
  
  <p>If I want to verify the certificate, do I have to check the chain and verify the last one in the chain, assuming that this is a root certificate?</p>
  
  <p>Is there a better way to do it?</p>