请教用X.509进行数字签名和验证的问题。请大家帮忙,谢谢。

peng0731 2008-12-27 12:10:56
使用X.509对XML文件进行签名。
代码如下:
X509Certificate2 cert = 从数字签名列表取得证书。
SignedXml signedXml = new SignedXml( Doc );
signedXml.SigningKey = cert.PrivateKey;

Reference reference = new Reference();
reference.Uri = "";

XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();
reference.AddTransform( env );

signedXml.AddReference( reference );

// Create a new KeyInfo object.
KeyInfo keyInfo = new KeyInfo();

// Load the certificate into a KeyInfoX509Data object
// and add it to the KeyInfo object.
keyInfo.AddClause( new KeyInfoX509Data( cert ) );

// Add the KeyInfo object to the SignedXml object.
signedXml.KeyInfo = keyInfo;

// Compute the signature.
signedXml.ComputeSignature();

XmlElement xmlDigitalSignature = signedXml.GetXml();

Doc.DocumentElement.AppendChild( Doc.ImportNode( xmlDigitalSignature, true ) );

解密的代码如下:
1.直接使用CheckSignature
SignedXml signedXml = new SignedXml( Doc );

XmlNodeList nodeList = Doc.GetElementsByTagName( "Signature" );

if( nodeList.Count <= 0 )
{
throw new CryptographicException( "Verification failed: No Signature was found in the document." );
}

if( nodeList.Count >= 2 )
{
throw new CryptographicException( "Verification failed: More that one signature was found for the document." );
}

signedXml.LoadXml( ( XmlElement )nodeList[ 0 ] );

return signedXml.CheckSignature();

2.使用证书
Cert = 从数字签名列表里取得签名使用的证书
SignedXml signedXml = new SignedXml( Doc );

XmlNodeList nodeList = Doc.GetElementsByTagName( "Signature" );

if( nodeList.Count <= 0 )
{
throw new CryptographicException( "Verification failed: No Signature was found in the document." );
}

if( nodeList.Count >= 2 )
{
throw new CryptographicException( "Verification failed: More that one signature was found for the document." );
}

signedXml.LoadXml( ( XmlElement )nodeList[ 0 ] );

return signedXml.CheckSignature(Cert,false);

当以上签名和验证在同一个程序里时,可以正确执行。
但是当签名别的程序里,而验证在另外一个程序里时,验证是不能通过的。也就是A.exe生成的XML签名文件,在B.exe里不能验证通过。而在A.exe里可以通过。而且我使用的是相同的数字证书。
这是为什么?请大家帮忙,谢谢。
...全文
194 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
derelictangel 2008-12-28
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 net5i 的回复:]
搂主在A,B两个程序里面都是怎么验证的?能否贴出代码?
[/Quote]

PS:
我的目标是 ---->

^_^
peng0731 2008-12-27
  • 打赏
  • 举报
回复
谢谢net5i

应该设置这个XmlDocument对象的PreserveWhitespace属性false才行

我设置过的。签名和验证都是false。
// Create a new XML document.
XmlDocument xmlDoc = new XmlDocument();

// Format the document to ignore white spaces.
xmlDoc.PreserveWhitespace = false;

// Load the passed XML file using it's name.
xmlDoc.Load( txtReadFilePath.Text );
net5i 2008-12-27
  • 打赏
  • 举报
回复
XML电子签名。

搂主在使用XmlDocument对象装载这个XML文件之前,应该设置这个XmlDocument对象的PreserveWhitespace属性false才行
wuyq11 2008-12-27
  • 打赏
  • 举报
回复
net5i 2008-12-27
  • 打赏
  • 举报
回复
搂主在A,B两个程序里面都是怎么验证的?能否贴出代码?

110,534

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧