Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Signing XML documents with PowerShell
Add-Type -AssemblyName System.Security
function Sign-XML {
Param ( [xml]$xml, [System.Security.Cryptography.X509Certificates.X509Certificate2]$certificate )
[System.Security.Cryptography.xml.SignedXml]$signedXml = $NULL
$signedXml = New-Object System.Security.Cryptography.Xml.SignedXml -ArgumentList $xml
$signedXml.SigningKey = $certificate.PrivateKey
$keyInfo = New-Object System.Security.Cryptography.Xml.KeyInfo
$keyInfo.AddClause((New-Object System.Security.Cryptography.Xml.KeyInfoX509Data -ArgumentList $certificate))
$signedXml.KeyInfo = $keyInfo
$Reference = New-Object System.Security.Cryptography.Xml.Reference
$Reference.Uri = ""
$env = New-Object System.Security.Cryptography.Xml.XmlDsigEnvelopedSignatureTransform
$Reference.AddTransform($env);
$signedXml.AddReference($Reference)
$signedXml.ComputeSignature()
[System.Xml.XmlElement]$xmlSignature = $signedXml.GetXml()
#Add signature to end of xml file
[void]$xml.DocumentElement.AppendChild($xml.ImportNode($xmlSignature, $true))
if ($xml.FirstChild -is [system.xml.XmlDeclaration]) {
$xml.RemoveChild($xml.FirstChild);
}
$xml
}
function Verify-XmlSignature {
Param (
[xml]$signed,
[switch]$Force
)
# Grab signing certificate from document
$rawCertBase64 = $signed.DocumentElement.Signature.KeyInfo.X509Data.X509Certificate
if(-not $rawCertBase64){
throw 'Unable to locate signing certificate in signed document'
return
}
$rawCert = [convert]::FromBase64String($rawCertBase64)
$signingCertificate = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2 -ArgumentList @(,$rawCert)
[System.Security.Cryptography.Xml.SignedXml]$signedXml = New-Object System.Security.Cryptography.Xml.SignedXml -ArgumentList $signed
$XmlNodeList = $signed.GetElementsByTagName("Signature")
$signedXml.LoadXml([System.Xml.XmlElement] ($XmlNodeList[0]))
return $signedXml.CheckSignature($signingCertificate, $Force)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.