使用 PEM 证书在 Powershell 中验证 XML 签名

Verifying XML Signature in Powershell with PEM Certificate

我正在尝试创建一个 powershell 脚本,它将使用 XML 文档中的数据。但是,在做任何工作之前,我需要通过验证签名来验证 XML 没有被篡改。

我有一份 public 密钥的副本,用于签署 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)

但是,当它运行时我得到以下异常...

Exception calling "CheckSignature" with "2" argument(s): "SignatureDescription could not be created for the signature algorithm supplied." At line:34 char:1 + $Check = $SignedXml.CheckSignature($CertPath, $true) + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : CryptographicException

如有任何帮助,我们将不胜感激。谢谢!

经过一些深入的额外搜索,我发现 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# 示例