#digitally sign a file file using a PFX certificate creted on the fly
#the format of the signed file will be CAdES
#the script can be configured to use an existing PFX file or a certificate loaded from Microsoft Store (smart card certificate)

if ($args.Length -eq 0)
{
    echo "Usage: signpdf.ps1 <unsigned file> <signed file>"
}
else
{

#SignLib.dll and iTextSharp-4.1.6.dll are available here: ..\SignLib\netframework4.6.2
#Note that SignLib.dll with iTextSharp-4.1.6.dll (for PDF signatures) must be placed on a folder and the path must be added on the .ps1 file, as below:

$DllPath = 'SignLib.dll'
[System.Reflection.Assembly]::LoadFrom($DllPath)

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

    echo "Perform the digital signature..."

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

}