Assinar com certificado A3 XML

20/12/2018

8

Ola, tenho um xml gerado com as exigências da receita , porem estou com dificuldade em assinar com meu certificado a3.

Possuo esse codigo que assinar com a senha do certificado ja salva, mas nao estou conseguindo implentar no meu form.

//code

public static RSACryptoServiceProvider LerDispositivo(RSACryptoServiceProvider key, string PIN)
{
CspParameters csp = new CspParameters(key.CspKeyContainerInfo.ProviderType, key.CspKeyContainerInfo.ProviderName);
SecureString ss = new SecureString();
foreach (char a in PIN)
{
ss.AppendChar(a);
}
csp.ProviderName = key.CspKeyContainerInfo.ProviderName;
csp.ProviderType = key.CspKeyContainerInfo.ProviderType;
csp.KeyNumber = key.CspKeyContainerInfo.KeyNumber == KeyNumber.Exchange ? 1 : 2;
csp.KeyContainerName = key.CspKeyContainerInfo.KeyContainerName;
csp.KeyPassword = ss;
csp.Flags = CspProviderFlags.NoPrompt | CspProviderFlags.UseDefaultKeyContainer;

RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(csp);
return rsa;
}

public static XmlDocument Assinar(string mensagemXML, X509Certificate2 certificado)
{
System.Xml.XmlDocument xmlDoc = new XmlDocument();
RSACryptoServiceProvider Key = new RSACryptoServiceProvider();
SignedXml SignedDocument = default(SignedXml);
KeyInfo keyInfo = new KeyInfo();
xmlDoc.LoadXml(mensagemXML);

Key = (System.Security.Cryptography.RSACryptoServiceProvider)certificado.PrivateKey;
keyInfo.AddClause(new KeyInfoX509Data(certificado));
SignedDocument = new SignedXml(xmlDoc);

SignedDocument.SigningKey = Key;
SignedDocument.KeyInfo = keyInfo;
SignedDocument.SigningKey = LerDispositivo(Key, "12345");

Reference reference = new Reference();
reference.Uri = string.Empty;
reference.AddTransform(new XmlDsigEnvelopedSignatureTransform());
reference.AddTransform(new XmlDsigC14NTransform(true));
SignedDocument.AddReference(reference);
SignedDocument.ComputeSignature();
System.Xml.XmlElement xmlDigitalSignature = SignedDocument.GetXml();
xmlDoc.DocumentElement.AppendChild(xmlDoc.ImportNode(xmlDigitalSignature, true));

return xmlDoc;
}

Como consigo chamar na minha rotina de assinar. Obrigado
Responder