CodeSnip180x180The code example in this procedure demonstrates how to digitally sign an entire XML document with Powershell and attach the signature to the document in a <Signature> element.

The example creates an RSA signing key, and adds the key to a "non persistent" container.

After this, we verify the signatur on a example xml

  

 

First import the assambly 

[void][reflection.assembly]::Load('System.Security, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a')

 Next define a sample xml

[xml]  $ExampleXML = `
"<?xml version=""1.0"" encoding=""utf-8""?>
<root>
<so>
<user name = ""Andreas"">thats me</user>
<user name = ""Peter"">I like this</user>
</so>
</root>"

Here the functions to create the key, sign the xml and verify it

function Create-RSAKey {
    
    $cspParams = New-Object System.Security.Cryptography.CspParameters -ArgumentList 1
    $cspParams.Flags = [System.Security.Cryptography.CspProviderFlags]::UseArchivableKey
    $cspParams.KeyNumber = [int][System.Security.Cryptography.KeyNumber]::Exchange
    [System.Security.Cryptography.RSACryptoServiceProvider] $rsaKey = New-Object System.Security.Cryptography.RSACryptoServiceProvider -ArgumentList @(2048,$cspParams)
    
    #Nicht dauerhaft speichern
    $rsaKey.PersistKeyInCsp = $false;
    
    return $rsaKey
}

 

function Verify-XmlSignature {
    Param (
    [xml] $checkxml,
    [system.Security.Cryptography.RSA] $Key
    )
    
    [System.Security.Cryptography.Xml.SignedXml] $signedXml = New-Object System.Security.Cryptography.Xml.SignedXml -ArgumentList $checkxml
    $XmlNodeList = $checkxml.GetElementsByTagName("Signature")
	$signedXml.LoadXml([System.Xml.XmlElement] ($XmlNodeList[0]))
    $check = $signedXml.CheckSignature($key)
	return $check
}

 Example for the functions:

$Path = Split-Path $script:MyInvocation.MyCommand.Path
#Write-Host $Path

$Key = Create-RSAKey 
Sign-XML -xml $ExampleXML -rsaKey $Key
$ExampleXML.Save("$Path\myxml.xml")
$Checked = Verify-XmlSignature -checkxml $ExampleXML -Key $Key

Write-Host "Signature check status : " $Checked

 Export the Public key

$publicKey = [xml]$rsaKey.ToXmlString($false);
$PublicKey.Save("$Path\PublicKey.xml") 

Use it as String in your own code to verify your configuration:

	[xml] $PublicKey = "YOURKEY"
	
	$rsaProvider = New-Object System.Security.Cryptography.RSACryptoServiceProvider
	$rsaProvider.FromXmlString($PublicKey.InnerXml)
	
	$xml = New-Object xml

	$xml.load("MYXML.XML")
	
	$check = Verify-XmlSignature -checkxml $xml -Key $rsaProvider
	Write-Host "Check : $check" 

 

Downloads:

zipXML-Sign-Example Beliebt

Information
Erstelldatum 10.04.2014 11:18:05
Änderungsdatum 10.04.2014 13:19:15
Version
Dateigröße 1.49 KB
Erstellt von Andreas Nick
Geändert von Andreas Nick
Downloads 2.730
Lizenz
Preis