Em meu projeto, tenho uma regra que preciso assinar a string de um XML que tenho que está em base64 com o CPF do usuário...
Andei pesquisando, mas não consegui entender direito como que funciona essa assinatura de uma string com classes do próprio .NET.
Bem, achei esse link aqui que faz a assinatura de uma string de um XML de NF-e. Mas não consegui entender direito como que funciona, e nem como adaptar esse código desse tamanho para o meu cenário.
O que tenho até agora: Gero o XML, escrevo no arquivo e consigo gerar o hash base64 dessa string, mas o que me falta agora é assinar essa string com o CPF da pessoa.
Os códigos que tenho são:
//Cria o xml com as tags e faz o encoding para base64
var sb = new StringBuilder();
var settings = new XmlWriterSettings();
string cpf = "000.001.000-00";
using (var writer = XmlWriter.Create(sb, settings))
{
//Inicia o documetno xml
writer.WriteStartDocument();
//escreve o documento raiz
writer.WriteStartElement("no1");
//escreve os subelementos
writer.WriteElementString("no2", "valor");
//encerra o elemento raiz
writer.WriteEndElement();
//escreve o xml para o arquivo e encerra o objeto escritor
writer.Close();
}
//encoding do xml para base64
string s = EncodeTo64(sb.ToString());
//arquivo que vai ser usado para gerar a string base64
string caminho = parametros.Propriedades["ParPastaArquivoXML"].ToString();
caminho = caminho + "\\" + "arquivo.xml";
File.WriteAllText(caminho, s);
Aqui tenta assinar:
try
{
// Create a new CspParameters object to specify
// a key container.
CspParameters cspParams = new CspParameters();
cspParams.KeyContainerName = cpf;
// Create a new RSA signing key and save it in the container.
RSACryptoServiceProvider rsaKey = new RSACryptoServiceProvider(cspParams);
// Create a new XML document.
XmlDocument xmlDoc = new XmlDocument();
// Load an XML file into the XmlDocument object.
xmlDoc.PreserveWhitespace = false;
xmlDoc.Load(caminho);
// Sign the XML document.
SignXml(xmlDoc, rsaKey);
Console.WriteLine("XML file signed.");
// Save the document.
xmlDoc.Save(caminhoAssinado);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Aqui o método para assinar:
// Sign an XML file.
// This document cannot be verified unless the verifying
// code has the key with which it was signed.
public static void SignXml(XmlDocument xmlDoc, RSA Key)
{
// Check arguments.
if (xmlDoc == null)
throw new ArgumentException("xmlDoc");
if (Key == null)
throw new ArgumentException("Key");
// Create a SignedXml object.
SignedXml signedXml = new SignedXml(xmlDoc);
// Add the key to the SignedXml document.
signedXml.SigningKey = Key;
// Create a reference to be signed.
Reference reference = new Reference();
reference.Uri = "";
// Add an enveloped transformation to the reference.
XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();
reference.AddTransform(env);
// Add the reference to the SignedXml object.
signedXml.AddReference(reference);
// Compute the signature.
signedXml.ComputeSignature();
// Get the XML representation of the signature and save
// it to an XmlElement object.
XmlElement xmlDigitalSignature = signedXml.GetXml();
// Append the element to the XML document.
xmlDoc.DocumentElement.AppendChild(xmlDoc.ImportNode(xmlDigitalSignature, true));
}
O exemplo de XML que é criado segue abaixo:
<?xml version="1.0" encoding="utf-16"?>
<no1>
<no2>021303</no2>
</no1>
Até esse momento eu consigo gerar o hash base64.
Mas agora, como que eu faço para assinar esse hash com o CPF?