3

我正在尝试创建一个将使用 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。” 在 line:34 char:1 + $Check = $SignedXml.CheckSignature($CertPath, $true) + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : CryptographicException

任何帮助,将不胜感激。谢谢!

4

1 回答 1

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# 示例。

于 2015-06-10T15:21:24.733 回答