Já falamos aqui de Certificados e de como instala-los e configura-los, agora queria demostrar como fazeres um método por forma a que o possas ir buscar dinamicamente, em operações complexas tens de adiciona-lo a algum método que necessites. Ou seja, em vez de o processo de encriptação ser feito por relação de confiança entre Servidores, podes ir buscar o certificado à store e passa-lo num HttpRequest. Para tal basta saberes o Thumb Print como é lógico e foi explicado neste post Lê Aqui.
public static X509Certificate2 LoadCertificate(string ThumbPrint)
{
HttpContext webContext = HttpContext.Current;
// Retrieve the Local Machine certificate store and load the x.509
// client certificate, using the certificate's thumbprint to
// identify and retrieve it from the store.
try
{
webContext.Application.Lock();
X509Store x509Store = new X509Store(StoreLocation.LocalMachine);
X509Certificate2Collection x509Collection;
x509Store.Open(OpenFlags.ReadOnly);
x509Collection = x509Store.Certificates.Find(X509FindType.FindByThumbprint, ThumbPrint, false);
x509Store.Close();
if ((x509Collection.Count == 1))
{
X509Certificate2 certificate = x509Collection[0];
try
{
AsymmetricAlgorithm privateKey = certificate.PrivateKey;
}
catch
{
throw new ApplicationException(String.Format("Private key cannot be read for the certificate with thumbprint: {0}.
Ensure WinHTTPCertCfg.exe has been used to assign permissions to the IIS Application Pool Identity
(defaults to Network Service).", ThumbPrint));
}
webContext.Application["Certificate"] = certificate.GetRawCertData();
return certificate;
}
else
{
throw new ApplicationException("Certificate not found!");
}
}
catch (Exception ex)
{
if (ex.Message.Contains("Private key cannot be read"))
{
throw ex;
}
throw new ApplicationException(String.Format("Unable to retreive certificate with thumbprint: {0}", ThumbPrint), ex);
}
finally
{
try
{
webContext.Application.UnLock();
}
catch { }
}
}
Sem comentários:
Enviar um comentário