前端之家收集整理的这篇文章主要介绍了
.NET使用PFX文件签名XML文档,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
一个人如果下决心要成为什么样的人,或者下决心要做成什么样的事,那么,意志或者说动机的驱动力会使他心想事成,如愿以偿。
Program.cs代码:
class Program
{
static void Main(string[] args)
{
#region 1 - 加载XML文档
var xmlDoc = new XmlDocument();
xmlDoc.Load(XmlFile);
#endregion
#region 2 - 读取证书文件
var fs = new FileStream(CertificateFile,FileMode.Open);
var certBytes = new byte[fs.Length];
fs.Read(certBytes,0,(Int32)fs.Length);
fs.Close();
var cert = new X509Certificate2(certBytes);
#endregion
#region 3 - 签署xml文档
string signedXmlData = GetSignedXml(xmlDoc,cert);
#endregion
#region 4 - 根据证书验证签名的xml
bool isValid = Validate(signedXmlData,CertificateFile);
System.Console.WriteLine("Signed data validated: {0}",isValid);
#endregion
Console.ReadKey();
}
public static string CertificateFile { get { return string.Format("{0}\\{1}\\{2}",Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),"Data","certificate.pfx"); } }
public static string XmlFile { get { return string.Format("{0}\\{1}\\{2}","sample.xml"); } }
public static string GetSignedXml(XmlDocument xmlDocument,X509Certificate2 certificate)
{
var signedXml = new SignedXml(xmlDocument);
signedXml.SigningKey = certificate.PrivateKey;
var reference = new Reference();
reference.AddTransform(new XmlDsigEnvelopedSignatureTransform());
reference.AddTransform(new XmlDsigExcC14NTransform());
reference.Uri = "";
signedXml.AddReference(reference);
var keyInfo = new KeyInfo();
keyInfo.AddClause(new KeyInfoX509Data(certificate));
signedXml.KeyInfo = keyInfo;
signedXml.ComputeSignature();
xmlDocument.DocumentElement.AppendChild(signedXml.GetXml());
return xmlDocument.InnerXml;
}
public static bool Validate(string signedXmlData,string certPath)
{
bool validSender;
try
{
var assertion = new XmlDocument { PreserveWhitespace = true };
assertion.LoadXml(signedXmlData);
var ns = new XmlNamespaceManager(assertion.NaMetable);
ns.AddNamespace("ds",SignedXml.XmlDsigNamespaceUrl);
XmlNode signNode = assertion.SelectSingleNode("/ImportantData/ds:Signature",ns);
var signedXml = new SignedXml(assertion.DocumentElement);
signedXml.LoadXml(signNode as XmlElement);
var cert = new X509Certificate2(certPath);
if (!signedXml.CheckSignature(cert,true))
{
throw new SecurityException("Signature check Failed.");
}
else
{
validSender = true;
}
}
catch (Exception ex)
{
throw ex;
}
return validSender;
}
}
Sample.xml
<?xml version="1.0" encoding="utf-8" ?>
<ImportantData>
<EmployeeId>13232</EmployeeId>
<Password>ilikeworld</Password>
</ImportantData>
运行结果如图:
原文链接:https://www.f2er.com/xml/294722.html