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

peng0731 peng0731 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
使用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里可以通过。而且我使用的是相同的数字证书。
这是为什么?请大家帮忙,谢谢。
...全文
评论 5
收藏 已收藏
分享
返回顶部
peng0731
C# 111,129 成员 642,538 内容