The script signInCAdESFormat.ps1 signs a file of any type in the CAdES / PKCS#7 format from Windows PowerShell 5.1: a .p7m file that contains the signed file, or a detached .p7s signature. When the input is a .p7m file, the new signature is added to it (co-signature).
How to run it
powershell -ExecutionPolicy Bypass -File signInCAdESFormat.ps1 test.pdf signedFile.pdf.p7m
powershell -ExecutionPolicy Bypass -File signInCAdESFormat.ps1 contract.pdf -Detached
powershell -ExecutionPolicy Bypass -File signInCAdESFormat.ps1 contract.pdf.p7m contract.pdf.p7m
powershell -ExecutionPolicy Bypass -File signInCAdESFormat.ps1 contract.pdf -Level CadesA -TimestampUrl https://ca.signfiles.com/TSAServer.aspx
Options: -Level (Cms, CadesBes, CadesT, CadesC, CadesXL, CadesA, CadesLT, CadesLTA; all except Cms and CadesBes need -TimestampUrl), -Detached, -HashAlgorithm, -TimestampUrl, and the certificate options -PfxFile, -PfxPassword, -Thumbprint, -SmartCardPin.
The signing code of the script
Initialize-SignLib
if (-not $OutputFile)
{
if ($Detached) { $OutputFile = $InputFile + '.p7s' } else { $OutputFile = $InputFile + '.p7m' }
}
$sign = New-Object SignLib.Cades.CadesSignature (Get-SerialNumber $SerialNumber)
$sign.DigitalSignatureCertificate = Get-SigningCertificate -PfxFile $PfxFile -PfxPassword $PfxPassword -Thumbprint $Thumbprint -LocalMachine:$LocalMachine
$sign.SignatureStandard = [System.Enum]::Parse([SignLib.Cades.CadesSignatureStandard], $Level)
$sign.HashAlgorithm = Get-HashAlgorithm $HashAlgorithm
$sign.IsDetachedSignature = [bool]$Detached
if ($TimestampUrl) { $sign.TimeStamping.ServerUrl = [Uri]$TimestampUrl }
if (($Level -in @('CadesT', 'CadesC', 'CadesXL', 'CadesA', 'CadesLT', 'CadesLTA')) -and (-not $TimestampUrl)) { throw "The level $Level needs a time-stamping server (-TimestampUrl)." }
Write-Host "Perform the digital signature ($Level)..."
Set-SmartCardPin $SmartCardPin
[System.IO.File]::WriteAllBytes((Get-FullPath $OutputFile), $sign.ApplyDigitalSignature((Get-FullPath $InputFile)))
Write-Host "Signature file: $OutputFile"
Run the full sample. The script signInCAdESFormat.ps1 is in the folder PowerShell Scripts of the library download, with SignLib.dll, a test certificate and test documents. It runs in Windows PowerShell 5.1. Without a serial number the library runs in demo mode. Download the library and the samples · User manual
Frequently asked questions
How do I verify the P7M file from PowerShell?
With verifySignature.ps1 from the same folder; a .p7s file also needs -OriginalFile.