我正在尝试创建一个将在XML文档中使用数据的powershell脚本。但是,在进行任何工作之前,我需要通过验证签名来验证XML没有被篡改。
我有一份用于以PEM格式签署XML的证书的公钥副本,但我无法弄清楚如何让powershell使用该证书。
关闭我的工作是以下代码...
$Path = "data.xml"
$Xmldata = new-object Xml.XmlDocument
$Xmldata.PreserveWhitespace = $true
$Xmldata.Load($Path)
add-type -AssemblyName system.security
$SignedXml = New-Object System.Security.Cryptography.Xml.SignedXml -ArgumentList $Xmldata
$XmlNodeList = $Xmldata.EntitiesDescriptor.Signature
$XmlNodeList
$SignedXml.LoadXml($XmlNodeList)
$CertPath = "cert.pem"
$Check = $SignedXml.CheckSignature($CertPath, $true)
然而,当这次运行时,我得到以下异常......
使用“2”参数调用“CheckSignature”的异常: “无法为签名创建SignatureDescription 算法提供。“在线:34 char:1 + $ Check = $ SignedXml.CheckSignature($ CertPath,$ true) + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~ + CategoryInfo:NotSpecified:(:) [],MethodInvocationException + FullyQualifiedErrorId:CryptographicException
任何帮助将不胜感激。谢谢!
答案 0 :(得分:1)
经过一些激烈的额外搜索后,我发现SignedXML不支持http://www.w3.org/2001/04/xmldsig-more#rsa-sha256算法,必须手动添加。我必须在创建signedXML对象之前添加以下代码...
Add-Type @'
public class RSAPKCS1SHA256SignatureDescription : System.Security.Cryptography.SignatureDescription
{
public RSAPKCS1SHA256SignatureDescription()
{
base.KeyAlgorithm = "System.Security.Cryptography.RSACryptoServiceProvider";
base.DigestAlgorithm = "System.Security.Cryptography.SHA256Managed";
base.FormatterAlgorithm = "System.Security.Cryptography.RSAPKCS1SignatureFormatter";
base.DeformatterAlgorithm = "System.Security.Cryptography.RSAPKCS1SignatureDeformatter";
}
public override System.Security.Cryptography.AsymmetricSignatureDeformatter CreateDeformatter(System.Security.Cryptography.AsymmetricAlgorithm key)
{
System.Security.Cryptography.AsymmetricSignatureDeformatter asymmetricSignatureDeformatter = (System.Security.Cryptography.AsymmetricSignatureDeformatter)
System.Security.Cryptography.CryptoConfig.CreateFromName(base.DeformatterAlgorithm);
asymmetricSignatureDeformatter.SetKey(key);
asymmetricSignatureDeformatter.SetHashAlgorithm("SHA256");
return asymmetricSignatureDeformatter;
}
}
'@
$RSAPKCS1SHA256SignatureDescription = New-Object RSAPKCS1SHA256SignatureDescription
[System.Security.Cryptography.CryptoConfig]::AddAlgorithm($RSAPKCS1SHA256SignatureDescription.GetType(), "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256")
此解决方案改编自http://geekswithblogs.net/mkoerner/archive/2013/07/12/saml2-federationmetadata-validation.aspx中发现的同一问题的C#示例。