Created
February 10, 2017 05:13
-
-
Save malkafly/01cf3637d604c0a6f37a16f98b4b244f to your computer and use it in GitHub Desktop.
validar certificado A1
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class AppCertificadoDigital | |
{ | |
public string EmitidoPara { get; private set; } | |
public string EmitidoParaCnpj { get; private set; } | |
public string EmitidoPor { get; private set; } | |
public string NomeAmigavel { get; private set; } | |
public string Serial { get; private set; } | |
public DateTime Validade { get; private set; } | |
public AppCertificadoDigital() | |
{ | |
var store = new X509Store(StoreName.My, StoreLocation.CurrentUser); | |
store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly); | |
var collection = store.Certificates; | |
var fcollection = collection.Find(X509FindType.FindByTimeValid, DateTime.Now, true); | |
var scollection = X509Certificate2UI.SelectFromCollection(fcollection, "Certificados válidos:", | |
"Selecione o certificado que deseja usar", | |
X509SelectionFlag.SingleSelection); | |
if (scollection.Count == 0) | |
{ | |
return; | |
throw new Exception("Nenhum certificado foi selecionado!"); | |
} | |
foreach (var x509 in scollection) | |
{ | |
try | |
{ | |
EmitidoPara = ObterSubjectName(x509.SubjectName); | |
EmitidoParaCnpj = ObterSubjectNameCnpj(x509.SubjectName); | |
EmitidoPor = ObterIssuerName(x509.IssuerName); | |
NomeAmigavel = x509.FriendlyName.ToStringSafe(); | |
Serial = x509.SerialNumber; | |
Validade = Convert.ToDateTime(x509.GetExpirationDateString()); | |
x509.Reset(); | |
} | |
catch (CryptographicException) | |
{ | |
Console.WriteLine("Não foi possível obter as informações do certificado selecionado!"); | |
} | |
} | |
store.Close(); | |
} | |
private static string ObterSubjectName(X500DistinguishedName subjectName) | |
{ | |
if (!string.IsNullOrEmpty(subjectName.Name)) | |
{ | |
// Extrai a Razão Social e o CNPJ da empresa do Certificado no formato -> Razão Social:xx.xxx.xxx/xxxx-xx | |
var subjectNameCompleto = subjectName.Name.Substring(0, subjectName.Name.IndexOf(",", StringComparison.InvariantCultureIgnoreCase)).TrimStart(); | |
if (subjectNameCompleto.Contains("CN=")) | |
subjectNameCompleto = subjectNameCompleto.Replace("CN=", "").TrimStart(); | |
return subjectNameCompleto; | |
} | |
throw new TcsGenericException(TipoErro.Erro, "O certificado atual não possui empresa associada!"); | |
} | |
private static string ObterSubjectNameRazaoSocial(X500DistinguishedName subjectName) | |
{ | |
var subjectNameCompleto = ObterSubjectName(subjectName); | |
// Extrai a Razão Social | |
return subjectNameCompleto.Substring(0, subjectNameCompleto.IndexOf(":", StringComparison.InvariantCultureIgnoreCase)); | |
} | |
private static string ObterSubjectNameCnpj(X500DistinguishedName subjectName) | |
{ | |
var subjectNameCompleto = ObterSubjectName(subjectName); | |
// Extrai o CNPJ | |
return subjectNameCompleto.Substring( | |
subjectNameCompleto.IndexOf(":", StringComparison.InvariantCultureIgnoreCase), | |
subjectNameCompleto.Length - ObterSubjectNameRazaoSocial(subjectName).Length) | |
.Replace(":", "") | |
.Replace(".", "") | |
.Replace("/", "") | |
.Replace("-", ""); | |
} | |
private static string ObterIssuerName(X500DistinguishedName issuerName) | |
{ | |
if (!string.IsNullOrEmpty(issuerName.Name)) | |
{ | |
var issuerNameCompleto = | |
issuerName.Name.Substring(0, issuerName.Name.IndexOf(",", StringComparison.InvariantCultureIgnoreCase)) | |
.TrimStart(); | |
if (issuerNameCompleto.Contains("CN=")) | |
issuerNameCompleto = issuerNameCompleto.Replace("CN=", "").TrimStart(); | |
return issuerNameCompleto; | |
} | |
throw new TcsGenericException(TipoErro.Erro, "O certificado atual não possui fabricante associado!"); | |
} | |
public static X509Certificate2 BuscarCertificado(string numeroSerial) | |
{ | |
X509Certificate2 certificado = null; | |
if (string.IsNullOrEmpty(numeroSerial)) | |
throw new TcsGenericException(TipoErro.Erro, "Impossível localizar o certificado digital!"); | |
var store = new X509Store(StoreName.My, StoreLocation.CurrentUser); | |
store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly); | |
foreach (var item in store.Certificates) | |
{ | |
if (item.SerialNumber != null && | |
item.SerialNumber.ToUpper() | |
.Equals(numeroSerial.ToUpper(), StringComparison.InvariantCultureIgnoreCase)) | |
certificado = item; | |
} | |
if (certificado == null) | |
throw new TcsGenericException(TipoErro.Erro, string.Format("Certificado digital nº {0} não encontrado!", numeroSerial.ToUpper())); | |
return certificado; | |
} | |
public static bool CompararCnpjCertificadoVsCertificadoEmpresa(string numeroSerial, string cnpjComparar) | |
{ | |
if (string.IsNullOrEmpty(cnpjComparar)) | |
throw new TcsGenericException(TipoErro.Aviso, "O CNPJ não foi informado!"); | |
X509Certificate2 certificado = BuscarCertificado(numeroSerial); | |
var cnpjCertificado = ObterSubjectNameCnpj(certificado.SubjectName); | |
cnpjComparar = cnpjComparar.Replace(".", "").Replace("/", "").Replace("-", ""); | |
if (!Validacao.CompararCnpjRaiz(cnpjCertificado, cnpjComparar)) | |
throw new TcsGenericException(TipoErro.Aviso, "O CNPJ contido no Certificado Digital selecionado não confere com o CNPJ da empresa atual!"); | |
return true; | |
} | |
public static List<X509Certificate2> ListarCertificados() | |
{ | |
List<X509Certificate2> list = new List<X509Certificate2>(); | |
var store = new X509Store(StoreName.My, StoreLocation.CurrentUser); | |
store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly); | |
foreach (var item in store.Certificates) | |
{ | |
if (item.SerialNumber != null) | |
{ | |
list.Add(item); | |
} | |
} | |
return list.OrderBy(ob => ob.NotAfter).ToList(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment