SignedXml.CheckSignature somente retorna true se eu verificar com a chave privada
-
20-12-2019 - |
Pergunta
Eu tenho visto várias questões semelhantes, mas nenhum que o endereço exatamente o que eu estou pedindo.
Eu estou tentando assinar um XML, em seguida, verifique-a com a chave pública usando C#.
Eu assinar o XML com uma chave, em seguida, exportar a chave para um XML.Em seguida, pegue a chave e o XML assinado para um computador diferente, importe a chave usando rsa.FromXmlString(doc.InnerXml)
, e verifique a assinatura XML.
Isso funciona se eu exportar as chaves pública e privada para um XML usando rsa.ToXmlString(True)
.No entanto, quero exportar apenas a minha chave pública usando rsa.ToXmlString(False)
.Se eu só exportar a chave pública e importá-lo no segundo computador e tente validar o XML signature ele diz que a assinatura não é válida.
Primeiro, eu deveria ser capaz de verificar o XML assinado, com apenas a chave pública?
Segundo, Se isso é verdade, por que a minha verifique XML função só funciona com a pub/priv par de chave e não apenas com a chave pública?
Você tem alguma sabedoria sobre como depurar esse problema?Eu não tenho certeza o que mais fazer, porque signedXml.CheckSignature(Key);
não fornece qualquer informação sobre o motivo da falha.
A minha chave de importação, de exportação chave, sinal de XML, e verifique as funções do XML estão abaixo.Deixe-me saber se você precisar de mais informações.
public static void ImportKeyFromFile(string ContainerName, string inputFile)
{
try
{
// Create new XmlDocument.
XmlDocument doc = new XmlDocument();
// Load XML Document.
doc.Load(inputFile);
// Create the CspParameters object and set the key container
// name used to store the RSA key pair.
CspParameters cp = new CspParameters();
cp.KeyContainerName = ContainerName;
// Create a new instance of RSACryptoServiceProvider that accesses
// the key container MyKeyContainerName.
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(cp);
// Get RSA Parameters from xml document.
rsa.FromXmlString(doc.InnerXml);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
public static void ExportKeyToFile(string ContainerName, string outputPath, bool private_key)
{
try
{
// Create the CspParameters object and set the key container
// name used to store the RSA key pair.
CspParameters cp = new CspParameters();
cp.KeyContainerName = ContainerName;
// Create a new instance of RSACryptoServiceProvider that accesses
// the key container MyKeyContainerName.
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(cp);
// Create new XmlDocument.
XmlDocument doc = new XmlDocument();
// Store rsa key.
doc.InnerXml = rsa.ToXmlString(private_key);
// Save Document.
doc.Save(outputPath);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
public static Boolean VerifyXml(XmlDocument Doc, RSA Key)
{
// Check arguments.
if (Doc == null)
throw new ArgumentException("Doc");
if (Key == null)
throw new ArgumentException("Key");
// Create a new SignedXml object and pass it
// the XML document class.
SignedXml signedXml = new SignedXml(Doc);
// Find the "Signature" node and create a new
// XmlNodeList object.
XmlNodeList nodeList = Doc.GetElementsByTagName("Signature");
// Throw an exception if no signature was found.
if (nodeList.Count <= 0)
{
throw new CryptographicException("Verification failed: No Signature was found in the document.");
}
// Load the first <signature> node.
signedXml.LoadXml((XmlElement)nodeList[0]);
// Check the signature and return the result.
return signedXml.CheckSignature(Key);
}
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));
}
Solução
O problema é porque você não pode armazenar chaves públicas em um Recipiente de Chave.Para verificar uma assinatura, com apenas uma chave pública, você deve importar a chave do XML usando rsa.FromXmlString
em seguida, passe rsa diretamente para a verificação da Assinatura da função.Se você tentar armazenar uma chave pública em um recipiente de chave e recuperá-la mais tarde você vai acabar criando uma nova chave.Como armazenar uma chave pública em um nível de máquina contêiner de chave RSA