Created
August 26, 2015 13:48
-
-
Save lucasselliach/d251392ff58f324468af to your computer and use it in GitHub Desktop.
Buscar Certificado digital no computador e realizar a assinatura para ativação do dispositivo SAT
This file contains 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 static class CertificadoDigital | |
{ | |
public static X509Certificate2 BuscaCertificado() | |
{ | |
var x509Cert = new X509Certificate2(); | |
try | |
{ | |
var store = new X509Store(StoreLocation.CurrentUser); | |
store.Open(OpenFlags.ReadOnly); | |
var collection = (X509Certificate2Collection)store.Certificates; | |
var scollection = X509Certificate2UI.SelectFromCollection(collection, "Certificado(s) Digital(is) disponível(is)", "Selecione o Certificado Digital para uso no aplicativo", X509SelectionFlag.SingleSelection); | |
if (scollection.Count == 0) | |
{ | |
x509Cert.Reset(); | |
} | |
else | |
{ | |
x509Cert = scollection[0]; | |
} | |
store.Close(); | |
return x509Cert; | |
} | |
catch (Exception ex) | |
{ | |
Console.WriteLine(ex.Message); | |
return x509Cert; | |
} | |
} | |
public static string AssinarAplicativoComercialSat(X509Certificate2 certificadoSelecionado, string cnpjs) | |
{ | |
try | |
{ | |
if(!certificadoSelecionado.HasPrivateKey) throw new Exception("Certificado sem chave privada! Chave privada é necessaria!"); | |
var dataParaCriptografar = Encoding.UTF8.GetBytes(cnpjs); | |
var key = new RSACryptoServiceProvider(); | |
key.FromXmlString(certificadoSelecionado.PrivateKey.ToXmlString(true)); | |
var encrypted = key.SignData(dataParaCriptografar, CryptoConfig.MapNameToOID("SHA256")); | |
return Convert.ToBase64String(encrypted); | |
} | |
catch (Exception ex) | |
{ | |
throw new Exception("Erro ao assinar arquivo. A mensagem retornada foi: " + ex.Message); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment