CAdES, P7M, P7S Digital Signature in PowerShell

#How to run the PowerShell scripts

#SignLib.dll must be placed on a folder and the path must be added on the .ps1 script
#$DllPath = 'd:\SignLib.dll'
#[System.Reflection.Assembly]::LoadFrom($DllPath)

#run the script file from command line, as below:
#powershell -executionPolicy bypass -file cadesSign.ps1 "d:\test.txt" "d:\test.txt.p7s"

#Digitally sign a file in CAdES format using a PFX certificate.
if ($args.Length -eq 0)
{
echo "Usage: cadesSign.ps1 <unsigned file> <signed file>"
}
else
{
$DllPath = 'd:\SignLib.dll'
[System.Reflection.Assembly]::LoadFrom($DllPath)

$pfxFilePath = "d:\pfxcertificate.pfx"
$pFXFilePassword = "123456"

#digitally sign the file in CAdES format
$sign = new-object -typeName SignLib.Cades.CadesSignature("")
$sign.DigitalSignatureCertificate = [SignLib.Certificates.DigitalCertificate]::LoadCertificate($pfxFilePath, $pFXFilePassword)

#Load the certificate from Microsoft Certificate Store (smart card certificates).
#$sign.DigitalSignatureCertificate = [SignLib.Certificates.DigitalCertificate]::LoadCertificate($false, "","","");

#set the hashing algorithm
$sign.HashAlgorithm = [SignLib.HashAlgorithm]::SHA256;

#set the digital signature standard
$sign.SignatureStandard = [SignLib.Cades.CadesSignatureStandard]::CadesBes;

echo "Perform the digital signature..."

[System.IO.File]::WriteAllBytes($args[1], $sign.ApplyDigitalSignature($args[0]));
}

See also: