public HttpResponseMessage Post(X509KeyModel model)
        {
            if (!ModelState.IsValid)
            {
                return Request.CreateResponse(HttpStatusCode.BadRequest, ModelState.GetErrors());
            }

            if (this.config.Keys.All.Any(x => x.Name == model.Name))
            {
                ModelState.AddModelError("", "That Name is already in use.");
                return Request.CreateResponse(HttpStatusCode.BadRequest, ModelState.GetErrors());
            }

            var key = new X509CertificateReference();
            key.Name = model.Name;
            key.StoreName = System.Security.Cryptography.X509Certificates.StoreName.My;
            key.Location = System.Security.Cryptography.X509Certificates.StoreLocation.LocalMachine;
            key.FindType = System.Security.Cryptography.X509Certificates.X509FindType.FindByThumbprint;
            key.FindValue = model.Thumbprint;

            var cert = key.Certificate;
            if (cert == null)
            {
                ModelState.AddModelError("", "Invalid Values For Certificate");
                return Request.CreateResponse(HttpStatusCode.BadRequest, ModelState.GetErrors());
            }

            try
            {
                var tmp = cert.PrivateKey;
            }
            catch (CryptographicException)
            {
                ModelState.AddModelError("", "No Read Access to Private Key of Certificate");
                return Request.CreateResponse(HttpStatusCode.BadRequest, ModelState.GetErrors());
            }

            if (model.FindType != FindType.Thumbprint)
            {
                key.FindType = System.Security.Cryptography.X509Certificates.X509FindType.FindBySubjectDistinguishedName;
                key.FindValue = cert.Subject;
                try
                {
                    cert = key.Certificate;
                }
                catch (InvalidOperationException)
                {
                    ModelState.AddModelError("", "Multiple certificates match that subject name");
                    return Request.CreateResponse(HttpStatusCode.BadRequest, ModelState.GetErrors());
                }
            }

            this.config.Keys.Add(key);
            this.config.SaveChanges();

            return Request.CreateResponse(HttpStatusCode.OK, new X509KeyModel(key));
        }
 public X509KeyModel(X509CertificateReference key)
 {
     this.ID = key.ID;
     this.Name = key.Name;
     this.FindType =
         key.FindType == System.Security.Cryptography.X509Certificates.X509FindType.FindByThumbprint ?
         FindType.Thumbprint : Models.FindType.SubjectName;
     if (key.Certificate != null)
     {
         this.Thumbprint = key.Certificate.Thumbprint;
     }
 }