Pages

Showing posts with label Scripting. Show all posts
Showing posts with label Scripting. Show all posts

Tuesday, June 13, 2023

PowerShell Script that will use the OneTimeSecret service to generate and return a URL to access a password

One of the frequent questions I have been asked after my post:

Using Microsoft Forms and Logic App to create an automated submissions and approval process for Azure AD User Creation
http://terenceluk.blogspot.com/2023/04/using-microsoft-forms-and-logic-app-to.html

… was whether there is a more secured way to include the password of the newly created user in an email rather than just pasting it into the confirmation email. The main reason why I chose to include the password in plain text is because the password is temporary and would require the user to change upon successfully log on. Nevertheless, I’ve always preached that passwords should never be included in email so I would like to provide an alternate way to better the protection with the included the password.

The method I would recommend is to use a service such as OneTimeSecret that allows you to provide a link to a page that provides the password and this link can only be opened once and it has an expiry. The following is a PowerShell script that can be used in an Automation Account with a webhook that receives a passed password, uses OneTimeSecret to create a link, then return that link.

The PowerShell script can be found at my following GitHub repo: https://github.com/terenceluk/Azure/blob/main/PowerShell/Generate-OneTimeSecret-URL.ps1

image

Thursday, February 18, 2021

Using PowerShell to Batch Password Protect Adobe PDF Files in a Directory

As a follow up to my previous post:

Attempting to use itextsharp.dll throws the error: "Could not load file or assembly 'BouncyCastle.Crypto, Version=1.8.6.0, Culture=neutral, PublicKeyToken=0e99375e54769942'..."

http://terenceluk.blogspot.com/2021/02/attempting-to-use-itextsharpdll-throws.html

… the script provided in the blog post did not match the requirements I needed so I’ve gone ahead to modify it and created two versions:

  1. Uses an Excel spreadsheet with predefined passwords to password protect PDF documents and fills in the name of the file
  2. Uses an Excel spreadsheet to fill in PDF file names and the randomly generated password used to password protect it

The following are the two PowerShell scripts:

Using PowerShell to Password Protect Adobe PDF Files (requires only passwords)

The following describes how to use PowerShell to password protect Adobe PDF files with a reference spreadsheet with only the passwords defined. The PowerShell script’s logic is as follows:

  1. Opens up a spreadsheet with two columns:
    1. Source Name < blank
    2. Password < password specified
  2. Looks into a directory and begins password protecting the documents with the passwords in the spreadsheet AND fills in the source name column with the file name
  3. Saves the PDF into another directory

1. Begin by creating a spreadsheet with two columns leaving the Source Name blank with the Password column filled in:

    a) Source Name

    b) Password

image

2. Proceed by creating a .ps1 file from the following code (also attached as PasswordProtectPDF.ps1):

Add-Type -Path "C:\itextsharp.5.5.13.2\lib\BouncyCastle.Crypto.dll"

[System.Reflection.Assembly]::LoadFrom("itextsharp.dll")

function PSUsing {

param (

[System.IDisposable] $excelSheetNumbernputObject = $(throw "The parameter -inputObject is required."),

[ScriptBlock] $scriptBlock = $(throw "The parameter -scriptBlock is required.")

)

Try {

&$scriptBlock

}

Finally {

if ($excelSheetNumbernputObject.psbase -eq $null) {

$excelSheetNumbernputObject.Dispose()

} else {

$excelSheetNumbernputObject.psbase.Dispose()

}

}

}

$sourcePath = "C:\PDF\"

$destinationPath = "C:\PDF\WithPassword\"

$excelReferenceSheet = "c:\ScriptsNew\PDFList.xlsx"

$xlCellTypeLastCell = 11

$startRow,$col=2,1

$excelSheetNumber=1

# OPEN EXCEL FILE WITH PASSWORDS

$excel=new-object -com excel.application

$excel.DisplayAlerts = $false

$excel.Visible = $false

$workbook=$excel.workbooks.open($excelReferenceSheet)

$worksheet=$workbook.Sheets.Item($excelSheetNumber)

$rowIncrement=0;

# BEGIN TRAVERSING THROUGH SOURCE FOLDER

$files = Get-ChildItem "C:\PDF\\*" -file

foreach ($f in $files){

# WRITE SOURCE FILE NAME INTO SPREADSHEET

#Write-Output $f.name

$worksheet.Cells.Item($startRow + $rowIncrement,$col) = $f.name

#RETRIEVE PASSWORD FROM EXCEL

$password=$worksheet.Cells.Item($startRow + $rowIncrement,$col+1).Value2

#Write-Output $password

$rowIncrement++

$fullSourcePathAndFileName = $sourcePath + $f.name

$destinationPathAndFileName = $destinationPath + $f.name

# PASSWORD PROTECT PDF

New-Object PSObject -Property @{Source=$sourcePath + $sourceFileName;Destination=$destinationFileName;Password=$password}

$file = New-Object System.IO.FileInfo $fullSourcePathAndFileName

$fileWithPassword = New-Object System.IO.FileInfo $destinationPathAndFileName

PSUsing ( $fileStreamIn = $file.OpenRead() ) {

PSUsing ( $fileStreamOut = New-Object System.IO.FileStream($fileWithPassword.FullName,[System.IO.FileMode]::Create,[System.IO.FileAccess]::Write,[System.IO.FileShare]::None) ) {

PSUsing ( $reader = New-Object iTextSharp.text.pdf.PdfReader $fileStreamIn ) {

[iTextSharp.text.pdf.PdfEncryptor]::Encrypt($reader, $fileStreamOut, $true, $password, $password, [iTextSharp.text.pdf.PdfWriter]::ALLOW_PRINTING)

}

}

}

}

$workbook.SaveAs($excelReferenceSheet)

$excel.Close

$excel.Quit()

[System.GC]::Collect()

[System.GC]::WaitForPendingFinalizers()

[System.Runtime.Interopservices.Marshal]::ReleaseComObject($worksheet)

[System.Runtime.Interopservices.Marshal]::ReleaseComObject($excel)

Remove-Variable -Name excel

3. Open the ps1 script and edit the 3 paths as highlighted in red above:

$sourcePath = "C:\PDF\" <-- Directory containing the source PDFs

$destinationPath = "C:\PDF\WithPassword\" <-- Directory containing the source PDFs

$excelReferenceSheet = "c:\ScriptsNew\PDFList.xlsx" <-- Directory where the spreadsheet that the script will reference for the PDF file name and password

$files = Get-ChildItem "C:\PDF\\*" -file <-- Update the C:\PDF to the directory containing the source PDFs

4. Download the following .nupkg packages:

iTextSharp 5.5.13.2
https://www.nuget.org/packages/iTextSharp/

BouncyCastle 1.8.6.1
https://www.nuget.org/packages/BouncyCastle/1.8.6.1

Rename the .nupkg extension to .zip, extract them to a folder and then copy the itextsharp.dll and BouncyCastle.Crypto.dll files

5. Create the directory where the password protected PDF files will be stored.

6. Proceed to execute the PowerShell script to password protect PDFs.

image

7. New PDFs should be created in the destination directory upon successfully executing the PowerShell script.

image

8. The spreadsheet referenced for configuring the passwords will have the Source Name column filled in with the file names of the password protected PDFs:

image

Using PowerShell to Password Protect Adobe PDF Files (auto generate passwords)

The following describes how to use PowerShell to password protect Adobe PDF files with a reference spreadsheet with only the passwords defined. The PowerShell script’s logic is as follows:

  1. Opens up a spreadsheet with two columns:
    1. Source Name < blank
    2. Password < password specified
  2. Looks into a directory and begins password protecting the documents with the passwords in the spreadsheet AND fills in the source name column with the file name
  3. Saves the PDF into another directory

1. Begin by creating a spreadsheet with two columns leaving the Source Name and Password columns blank:

    a) Source Name

    b) Password

image

2. Proceed by creating a .ps1 file from the following code (also attached as PasswordProtectPDF.ps1):

Add-Type -Path "C:\itextsharp.5.5.13.2\lib\BouncyCastle.Crypto.dll"

Add-Type -AssemblyName System.Web

[System.Reflection.Assembly]::LoadFrom("itextsharp.dll")

function PSUsing {

param (

[System.IDisposable] $excelSheetNumbernputObject = $(throw "The parameter -inputObject is required."),

[ScriptBlock] $scriptBlock = $(throw "The parameter -scriptBlock is required.")

)

Try {

&$scriptBlock

}

Finally {

if ($excelSheetNumbernputObject.psbase -eq $null) {

$excelSheetNumbernputObject.Dispose()

} else {

$excelSheetNumbernputObject.psbase.Dispose()

}

}

}

$sourcePath = "C:\PDF\"

$destinationPath = "C:\PDF\WithPassword\"

$excelReferenceSheet = "C:\Scripts-GeneratePassword\PDFList.xlsx"

$xlCellTypeLastCell = 11

$startRow,$col=2,1

$excelSheetNumber=1

$passwordLength = 15

$numberOfSpecialCharacters = 4

# OPEN EXCEL FILE TO FILL OUT PDF FILENAME AND PASSWORDS

$excel=new-object -com excel.application

$excel.DisplayAlerts = $false

$excel.Visible = $false

$workbook=$excel.workbooks.open($excelReferenceSheet)

$worksheet=$workbook.Sheets.Item($excelSheetNumber)

$rowIncrement=0;

# BEGIN TRAVERSING THROUGH SOURCE FOLDER

$files = Get-ChildItem "C:\PDF\\*" -file

foreach ($f in $files){

# WRITE SOURCE FILE NAME INTO SPREADSHEET

#Write-Output $f.name

$worksheet.Cells.Item($startRow + $rowIncrement,$col) = $f.name

#GENERATE RANDOM PASSWORD AND FILL OUT SPREADSHEET

$password = [System.Web.Security.Membership]::GeneratePassword($passwordLength,$numberOfSpecialCharacters)

$worksheet.Cells.Item($startRow + $rowIncrement,$col+1).Value2 = $password

#Write-Output $password

$rowIncrement++

$fullSourcePathAndFileName = $sourcePath + $f.name

$destinationPathAndFileName = $destinationPath + $f.name

# PASSWORD PROTECT PDF

New-Object PSObject -Property @{Source=$sourcePath + $sourceFileName;Destination=$destinationFileName;Password=$password}

$file = New-Object System.IO.FileInfo $fullSourcePathAndFileName

$fileWithPassword = New-Object System.IO.FileInfo $destinationPathAndFileName

PSUsing ( $fileStreamIn = $file.OpenRead() ) {

PSUsing ( $fileStreamOut = New-Object System.IO.FileStream($fileWithPassword.FullName,[System.IO.FileMode]::Create,[System.IO.FileAccess]::Write,[System.IO.FileShare]::None) ) {

PSUsing ( $reader = New-Object iTextSharp.text.pdf.PdfReader $fileStreamIn ) {

[iTextSharp.text.pdf.PdfEncryptor]::Encrypt($reader, $fileStreamOut, $true, $password, $password, [iTextSharp.text.pdf.PdfWriter]::ALLOW_PRINTING)

}

}

}

}

$workbook.SaveAs($excelReferenceSheet)

$excel.Close

$excel.Quit()

[System.GC]::Collect()

[System.GC]::WaitForPendingFinalizers()

[System.Runtime.Interopservices.Marshal]::ReleaseComObject($worksheet)

[System.Runtime.Interopservices.Marshal]::ReleaseComObject($excel)

Remove-Variable -Name excel

3. Open the ps1 script and edit the 3 paths as highlighted in red above:

$sourcePath = "C:\PDF\" <-- Directory containing the source PDFs

$destinationPath = "C:\PDF\WithPassword\" <-- Directory containing the source PDFs

$excelReferenceSheet = "c:\ScriptsNew\PDFList.xlsx" <-- Directory where the spreadsheet that the script will reference for the PDF file name and password

$passwordLength = 15 <-- The length of the randomly generated password

$numberOfSpecialCharacters = 4 <-- The amount of non-numerical special characters in the password (e.g. !, -, $, &, @, #, %, etc)

$files = Get-ChildItem "C:\PDF\\*" -file <-- Update the C:\PDF to the directory containing the source PDFs

4. Download the following .nupkg packages:

iTextSharp 5.5.13.2

https://www.nuget.org/packages/iTextSharp/

BouncyCastle 1.8.6.1

https://www.nuget.org/packages/BouncyCastle/1.8.6.1

Rename the .nupkg extension to .zip, extract them to a folder and then copy the itextsharp.dll and BouncyCastle.Crypto.dll files

5. Create the directory where the password protected PDF files will be stored.

6. Proceed to execute the PowerShell script to password protect PDFs.

image

7. New PDFs should be created in the destination directory upon successfully executing the PowerShell script.

image

8. The spreadsheet referenced for configuring the passwords will have the Source Name column filled in with the file names and corresponding passwords of the password protected PDFs:

image

Batch converting Microsoft Word .doc to .docx with VBA

I was recently asked to provide an way to batch process a set of Microsoft Word documents that are still saved in the older .doc format to the modern .docx format and I wasn’t able to find a script that did exactly what I wanted so ended up writing one for the client. Coding isn’t my forte given it is not something I commonly perform so I thought I’d write this blog post for anyone who may be looking for something similar as well as have it for myself to reference in the future.

The following demonstrates how to open .doc documents in a specified folder and save them as .docx.

1. Begin by launching Word, click on the Developer tab and click on Visual Basic: 

image

2. Click on the Insert tab and then Module:

image

3. Paste the following code into the module:

Sub UpdateOldDocToDocx()

    Application.ScreenUpdating = False

    'Disable privacy settings warning

    Application.DisplayAlerts = False

    Dim oldDocument As Document

    Dim strPassword As String, strFile As String, strFolder, strDestFolder As String

    Dim passwordRow As Integer

    strFolder = "C:\Word\"

    strFile = Dir(strFolder & "*.doc", vbNormal)

    strDestFolder = "C:\Word\Upgraded\"

    ' BEGIN LOOPING THROUGH OLD WORD DOCUMENTS

    While strFile <> ""

      Set oldDocument = Documents.Open(FileName:=strFolder & strFile)

      'OPEN WORD, SAVE AND CLOSE

      With oldDocument

        .SaveAs2 FileName:=strDestFolder & strFile & "x", FileFormat:=wdFormatXMLDocument, CompatibilityMode:=15

        .Close

      End With

      strFile = Dir()

      Wend

End Sub

6. Update the variables to desired values:

strFolder: Where the source files are (ensure that the trailing "\" is in the path)

strDestFolder: Where the destination password protected files should be

(ensure that the trailing "\" is in the path)

7. Proceed to run the module by clicking on the play button or F5:

image

8. The upgraded files should be present in the defined directory:

imageimage

Wednesday, February 17, 2021

Using Microsoft Excel and Word VBA to batch password protect documents

I was recently asked to provide an way to batch process a set of Microsoft Excel and Word documents to password protect them and managed to use VBA to accomplish this. Coding isn’t something I commonly perform so I thought I’d write this blog post for anyone who may be looking for something similar as well as have it for myself to reference in the future.

Using an Excel Spreadsheet with passwords to password protect Excel files

1. Begin by creating an Excel spreadsheet with two columns and fill in the Password column with as many rows of passwords as there are Excel files to encrypt:

image

2. Save the file at a location that is outside of the folder containing the Excel files to encrypt. We will use C:\temp for this example.

image

3. Launch Excel, click on the Developer tab and click on Visual Basic:

image

4. Click on the Insert tab and then Module:

image

5. Paste the following code into the module:

Sub ProtectMultiExcelWithOpenPasswordwithExcelReferenceFile()

     Application.ScreenUpdating = False

    'Disable privacy settings warning

     Application.DisplayAlerts = False

    Dim passwordListExcel As Workbook

    Dim protectThisWorkbook As Workbook

    Dim strPassword As String, strFile As String, strFolder, strDestFolder As String

    Dim passwordRow As Integer

    strFolder = "C:\Excel\"

    strFile = Dir(strFolder & "*.xlsx", vbNormal)

    strDestFolder = "C:\Excel\Encrypted\"

    ' OPEN THE EXCEL WORKBOOK WITH PASSWORDS

    Set passwordListExcel = Workbooks.Open("C:\temp\ExcelFiles.xlsx")

    'SET ROW TO START AT 2 IGNORING THE HEADER

    passwordRow = 2

    ' BEGIN LOOPING THROUGH EXCEL WORKBOOK TO SET PASSWORDS

    While strFile <> ""

      Set protectThisWorkbook = Workbooks.Open(Filename:=strFolder & strFile)

      strPassword = passwordListExcel.Worksheets("Sheet1").Range("B" & passwordRow).Formula

      'OPEN EXCEL, SET PASSWORD, SAVE AND CLOSE

      With protectThisWorkbook

        .Password = strPassword

        .SaveAs Filename:=strDestFolder & "Encrypted-" & strFile, Password:=strPassword

        .Close

      End With

      ' WRITE THE DOCUMENT NAME INTO THE CELL BESIDE THE PASSWORD IN THE REFERENCE SPREADSHEET

       passwordListExcel.Worksheets("Sheet1").Range("A" & passwordRow).Formula = strFile

      'INCREMENT THE ROW COUNT BY 1 TO GO TO THE NEXT ROW

      passwordRow = passwordRow + 1

      strFile = Dir()

      Wend

       passwordListExcel.Close True

      Set passwordListExcel = Nothing

End Sub

6. Update the variables to desired values:

strFolder: Where the source files are (ensure that the trailing "\" is in the path)

strDestFolder: Where the destination password protected files should be

(ensure that the trailing "\" is in the path)

Set passwordListExcel = Workbooks.Open("C:\temp\ExcelFiles.xlsx"): Update the path to where the spreadsheet with the passwords is located as created in step #1.

7. Proceed to run the module by clicking on the play button or F5:

image

8. Reopening the reference Excel spreadsheet will now have the encrypted document name filled out:

image

9. Encrypted files should be present in the defined directory:

Generate random passwords to password protect Excel files

The following demonstrates how use VBA code to generate random passwords, encrypt Excel files in a specified folder, write the Excel file name and the respective password into an Excel spreadsheet.

1. Begin by creating an Excel spreadsheet with two columns with the heading Document Name and Password:

image

2. Save the file at a location that is outside of the folder containing the Excel files to encrypt. We will use C:\temp for this example.

image

3. Launch Excel, click on the Developer tab and click on Visual Basic: 

image

4. Click on the Insert tab and then Module:

image

5. Paste the following code into the module: 

Function RandomString(Length As Integer)

Dim CharacterBank As Variant

Dim x As Long

Dim str As String

'Test Length Input

  If Length < 1 Then

    MsgBox "Length variable must be greater than 0"

    Exit Function

  End If

CharacterBank = Array("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", _

  "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", _

  "y", "z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "!", "@", _

  "#", "$", "%", "^", "&", "*", "A", "B", "C", "D", "E", "F", "G", "H", _

  "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", _

  "W", "X", "Y", "Z")

'Randomly Select Characters One-by-One

  For x = 1 To Length

    Randomize

    str = str & CharacterBank(Int((UBound(CharacterBank) - LBound(CharacterBank) + 1) * Rnd + LBound(CharacterBank)))

  Next x

'Output Randomly Generated String

  RandomString = str

End Function

Sub ProtectMultiExcelWithOpenPasswordwithExcelReferenceFile()

     Application.ScreenUpdating = False

    'Disable privacy settings warning

     Application.DisplayAlerts = False

    Dim passwordListExcel As Workbook

    Dim protectThisWorkbook As Workbook

    Dim strPassword As String, strFile As String, strFolder, strDestFolder As String

    Dim passwordRow As Integer

    Dim passwordLength As Integer

    strFolder = "C:\Excel\"

    strFile = Dir(strFolder & "*.xlsx", vbNormal)

    strDestFolder = "C:\Excel\Encrypted\"

    passwordLength = 14

    ' OPEN THE EXCEL WORKBOOK WITH PASSWORDS

   Set passwordListExcel = Workbooks.Open("C:\temp\ExcelFiles.xlsx")

    'SET ROW TO START AT 2 IGNORING THE HEADER

    passwordRow = 2

    ' BEGIN LOOPING THROUGH EXCEL WORKBOOK TO SET PASSWORDS

    While strFile <> ""

      Set protectThisWorkbook = Workbooks.Open(Filename:=strFolder & strFile)

      'GENERATE RANDOM PASSWORD WITH SPECIFIED LENGTH

      strPassword = RandomString(passwordLength)

      'OPEN EXCEL, SET PASSWORD, SAVE AND CLOSE

      With protectThisWorkbook

        .Password = strPassword

        .SaveAs Filename:=strDestFolder & "Encrypted-" & strFile, Password:=strPassword

        .Close

      End With

      ' WRITE THE DOCUMENT NAME INTO THE CELL BESIDE THE PASSWORD IN THE REFERENCE SPREADSHEET

      passwordListExcel.Worksheets("Sheet1").Range("A" & passwordRow).Formula = strFile

      ' WRITE THE PASSWORD INTO THE CELL IN THE REFERENCE SPREADSHEET

       passwordListExcel.Worksheets("Sheet1").Range("B" & passwordRow).Formula = strPassword

      'INCREMENT THE ROW COUNT BY 1 TO GO TO THE NEXT ROW

      passwordRow = passwordRow + 1

      strFile = Dir()

      Wend

       passwordListExcel.Close True

      Set passwordListExcel = Nothing

End Sub

6. Update the variables to desired values:

strFolder: Where the source files are (ensure that the trailing "\" is in the path)

strDestFolder: Where the destination password protected files should be

(ensure that the trailing "\" is in the path)

Set passwordListExcel = Workbooks.Open("C:\temp\ExcelFiles.xlsx"): Update the path to where the spreadsheet with the passwords is located as created in step #1.

7. Proceed to run the module by clicking on the play button or F5:

image

8. Reopening the reference Excel spreadsheet will now have the encrypted document name and password filled out:

image

9. Encrypted files should be present in the defined directory:

image

Using an Excel Spreadsheet with passwords to password protect Word files

The following demonstrates how to use an Excel spreadsheet with passwords to password protect a folder with Word files.

1. Begin by creating an Excel spreadsheet with two columns and fill in the Password column with as many rows of passwords as there are Word files to encrypt:

image

2. Save the file at a location that is outside of the folder containing the Excel files to encrypt. We will use C:\temp for this example.

image

3. Launch Word, click on the Developer tab and click on Visual Basic: 

image

4. Click on the Insert tab and then Module:

image

5. Paste the following code into the module:

Sub ProtectMultiDocWithOpenPasswordwithExcelReferenceFile()

    Application.ScreenUpdating = False

    'Disable privacy settings warning

    Application.DisplayAlerts = False

    Dim excelObject As Object

    On Error Resume Next

    Set excelObject = GetObject(, "Excel.Application")

    If Err Then

        Set excelObject = CreateObject("Excel.Application")

    End If

    On Error GoTo 0

    Dim passwordListExcel

    Dim protectThisDocument As Document

    Dim strPassword As String, strFile As String, strFolder, strDestFolder As String

    Dim passwordRow As Integer

  strFolder = "C:\Word\"

    strFile = Dir(strFolder & "*.docx", vbNormal)

    strDestFolder = "C:\Word\Encrypted\"

    ' OPEN THE EXCEL WORKBOOK WITH PASSWORDS

    Set passwordListExcel = excelObject.Workbooks.Open("C:\temp\WordFiles.xlsx")

    'SET ROW TO START AT 2 IGNORING THE HEADER

    passwordRow = 2

    ' BEGIN LOOPING THROUGH WORD WORKBOOK TO SET PASSWORDS

    While strFile <> ""

      Set protectThisDocument = Documents.Open(FileName:=strFolder & strFile)

      strPassword = passwordListExcel.Worksheets("Sheet1").Range("B" & passwordRow).Formula

      'OPEN WORD, SET PASSWORD, SAVE AND CLOSE

      With protectThisDocument

        .Password = strPassword

        .SaveAs2 FileName:=strDestFolder & "Encrypted-" & strFile, Password:=strPassword

        .Close

      End With

      ' WRITE THE DOCUMENT NAME INTO THE CELL BESIDE THE PASSWORD IN THE REFERENCE SPREADSHEET

      passwordListExcel.Worksheets("Sheet1").Range("A" & passwordRow).Formula = strFile

      'INCREMENT THE ROW COUNT BY 1 TO GO TO THE NEXT ROW

      passwordRow = passwordRow + 1

      strFile = Dir()

      Wend

      passwordListExcel.Close True

      Set passwordListExcel = Nothing

End Sub

6. Update the variables to desired values:

strFolder: Where the source files are (ensure that the trailing "\" is in the path)

strDestFolder: Where the destination password protected files should be

(ensure that the trailing "\" is in the path)

Set passwordListExcel = Workbooks.Open("C:\temp\WordFiles.xlsx"): Update the path to where the spreadsheet with the passwords is located as created in step #1.

7. Proceed to run the module by clicking on the play button or F5:

image

8. Reopening the reference Excel spreadsheet will now have the encrypted document name filled out:

image

9. Encrypted files should be present in the defined directory:

image

Generate random passwords to password protect Word files

The following demonstrates how use VBA code to generate random passwords, encrypt Word files in a specified folder, write the Word file name and the respective password into an Excel spreadsheet.

1. Begin by creating an Excel spreadsheet with two columns with the heading Document Name and Password:

image

2. Save the file at a location that is outside of the folder containing the Excel files to encrypt. We will use C:\temp for this example.

image

3. Launch Word, click on the Developer tab and click on Visual Basic: 

image

4. Click on the Insert tab and then Module:

image

5. Paste the following code into the module:

Function RandomString(Length As Integer)

Dim CharacterBank As Variant

Dim x As Long

Dim str As String

'Test Length Input

  If Length < 1 Then

    MsgBox "Length variable must be greater than 0"

    Exit Function

  End If

CharacterBank = Array("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", _

  "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", _

  "y", "z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "!", "@", _

  "#", "$", "%", "^", "&", "*", "A", "B", "C", "D", "E", "F", "G", "H", _

  "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", _

  "W", "X", "Y", "Z")

'Randomly Select Characters One-by-One

  For x = 1 To Length

    Randomize

    str = str & CharacterBank(Int((UBound(CharacterBank) - LBound(CharacterBank) + 1) * Rnd + LBound(CharacterBank)))

  Next x

'Output Randomly Generated String

  RandomString = str

End Function

Sub ProtectMultiDocWithOpenPasswordwithExcelReferenceFile()

    Application.ScreenUpdating = False

    'Disable privacy settings warning

    Application.DisplayAlerts = False

    Dim excelObject As Object

    On Error Resume Next

    Set excelObject = GetObject(, "Excel.Application")

    If Err Then

        Set excelObject = CreateObject("Excel.Application")

    End If

    On Error GoTo 0

    Dim passwordListExcel

    Dim protectThisDocument As Document

    Dim strPassword As String, strFile As String, strFolder, strDestFolder As String

    Dim passwordRow As Integer

    Dim passwordLength As Integer

    strFolder = "C:\Word\"

    strFile = Dir(strFolder & "*.docx", vbNormal)

   strDestFolder = "C:\Word\Encrypted\"

    passwordLength = 14

    ' OPEN THE EXCEL WORKBOOK WITH PASSWORDS

    Set passwordListExcel = excelObject.Workbooks.Open("C:\temp\WordFiles.xlsx")

    'SET ROW TO START AT 2 IGNORING THE HEADER

    passwordRow = 2

    ' BEGIN LOOPING THROUGH WORD WORKBOOK TO SET PASSWORDS

    While strFile <> ""

      Set protectThisDocument = Documents.Open(FileName:=strFolder & strFile)

      'GENERATE RANDOM PASSWORD WITH SPECIFIED LENGTH

      strPassword = RandomString(passwordLength)

      'OPEN WORD, SET PASSWORD, SAVE AND CLOSE

      With protectThisDocument

        .Password = strPassword

        .SaveAs2 FileName:=strDestFolder & "Encrypted-" & strFile, Password:=strPassword

        .Close

      End With

      ' WRITE THE DOCUMENT NAME INTO THE CELL BESIDE THE PASSWORD IN THE REFERENCE SPREADSHEET

      passwordListExcel.Worksheets("Sheet1").Range("A" & passwordRow).Formula = strFile

      ' WRITE THE PASSWORD INTO THE CELL IN THE REFERENCE SPREADSHEET

      passwordListExcel.Worksheets("Sheet1").Range("B" & passwordRow).Formula = strPassword

      'INCREMENT THE ROW COUNT BY 1 TO GO TO THE NEXT ROW

      passwordRow = passwordRow + 1

      strFile = Dir()

      Wend

      passwordListExcel.Close True

      Set passwordListExcel = Nothing

End Sub

6. Update the variables to desired values:

strFolder: Where the source files are (ensure that the trailing "\" is in the path)

strDestFolder: Where the destination password protected files should be

(ensure that the trailing "\" is in the path)

Set passwordListExcel = Workbooks.Open("C:\temp\WordFiles.xlsx"): Update the path to where the spreadsheet with the passwords is located as created in step #1.

7. Proceed to run the module by clicking on the play button or F5:

image

8. Reopening the reference Excel spreadsheet will now have the encrypted document name and password filled out:

image

9. Encrypted files should be present in the defined directory:

image

Tuesday, February 16, 2021

Attempting to use itextsharp.dll throws the error: "Could not load file or assembly 'BouncyCastle.Crypto, Version=1.8.6.0, Culture=neutral, PublicKeyToken=0e99375e54769942'..."

Problem

Those who are looking for a PowerShell script to batch password protect PDF documents will quickly come across the following post as returned by Google:

Password Protect PDF document using windows Powershell script
https://efcomputer.net.au/blog/password-protect-pdf-document/

The author provides the following PowerShell script that uses the itextsharp.dll:

[System.Reflection.Assembly]::LoadFrom("itextsharp.dll")

function PSUsing {

param (

[System.IDisposable] $inputObject = $(throw "The parameter -inputObject is required."),

[ScriptBlock] $scriptBlock = $(throw "The parameter -scriptBlock is required.")

)

Try {

&$scriptBlock

}

Finally {

if ($inputObject.psbase -eq $null) {

$inputObject.Dispose()

} else {

$inputObject.psbase.Dispose()

}

}

}

$xlCellTypeLastCell = 11

$startRow,$col=2,1

$excel=new-object -com excel.application

$wb=$excel.workbooks.open("c:\temp\PDFList.xlsx")

for ($i=1; $i -le $wb.sheets.count; $i++)

{

$j=0;

$sh=$wb.Sheets.Item($i)

$endRow=$sh.UsedRange.SpecialCells($xlCellTypeLastCell).Row

$rangeAddress=$sh.Cells.Item($startRow+1,$col).Address() + ":" +$sh.Cells.Item($endRow+1,$col).Address()

$sh.Range($rangeAddress).Value2 | foreach {

$contract=$sh.Cells.Item($startRow + $j,$col).Value2

$filesource = $sh.Cells.Item($startRow + $j,$col+1).Value2

$filedest = $sh.Cells.Item($startRow + $j,$col+2).Value2

$dob=$sh.Cells.Item($startRow + $j,$col+3).Value2

New-Object PSObject -Property @{Contract=$contract;Dob=$dob}

$file = New-Object System.IO.FileInfo $filesource

$fileWithPassword = New-Object System.IO.FileInfo $filedest

$password = $dob

PSUsing ( $fileStreamIn = $file.OpenRead() ) {

PSUsing ( $fileStreamOut = New-Object System.IO.FileStream($fileWithPassword.FullName,[System.IO.FileMode]::Create,[System.IO.FileAccess]::Write,[System.IO.FileShare]::None) ) {

PSUsing ( $reader = New-Object iTextSharp.text.pdf.PdfReader $fileStreamIn ) {

[iTextSharp.text.pdf.PdfEncryptor]::Encrypt($reader, $fileStreamOut, $true, $password, $password, [iTextSharp.text.pdf.PdfWriter]::ALLOW_PRINTING)

}

}

}

$j++

}

}

$excel.Workbooks.Close()

At the time of this writing in Feb 2021, clicking on the link provided by the author brings us https://sourceforge.net/projects/itextsharp/files/ which no longer provides a download to the file.

Googling the for “itextsharp” returns a link to iTextSharp 5.5.13.2 located here https://www.nuget.org/packages/iTextSharp/ with the description that version 7 has replaced it but still available to be downloaded (along with security patches in the future):

image

With the package extracted, we proceed replicate the spreadsheet as shown in the post:

image

Then while placing the itextsharp.dll file into the same directory as the PowerShell script, we execute it but receive the following error:

New-Object : Could not load file or assembly 'BouncyCastle.Crypto, Version=1.8.6.0, Culture=neutral, PublicKeyToken=0e99375e54769942' or one of its

dependencies. The system cannot find the file specified.

At C:\itextsharp.5.5.13.2\lib\PasswordProtectPDF.ps1:46 char:22

+ ... ( $reader = New-Object iTextSharp.text.pdf.PdfReader $fileStreamIn ) ...

+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

+ CategoryInfo : NotSpecified: (:) [New-Object], FileNotFoundException

+ FullyQualifiedErrorId : System.IO.FileNotFoundException,Microsoft.PowerShell.Commands.NewObjectCommand

image

Solution

The reason why the error above is presented is because the BouncyCastle.Crypto assembly is also needed for the PowerShell script. In addition to downloading:

iTextSharp 5.5.13.2
https://www.nuget.org/packages/iTextSharp/

We should also download the following BouncyCastle:

BouncyCastle 1.8.6.1
https://www.nuget.org/packages/BouncyCastle/1.8.6.1

image

**Note that the latest version 1.8.9 at the time of this writing does not work.

With the two packages downloaded, rename the extension .nupkg to .zip and unpack them into folders.

Place the following files into same directory:

  1. BouncyCastle.Crypto.dll
  2. itextsharp.dll
  3. PasswordProtectPDF.ps1 (this is the script provided by the author above)
image

Before executing the PowerShell script, make sure the following line is added to the beginning so that the BouncyCastle.Crypto.dll is loaded:

Add-Type -Path "C:\itextsharp.5.5.13.2\lib\BouncyCastle.Crypto.dll"

image

Proceeding to run the PowerShell script will now complete successfully:

image

If you prefer not to work in the ISE environment then the line can either be added directly into the PS1, or run the Add-Type -Path "C:\itextsharp.5.5.13.2\lib\BouncyCastle.Crypto.dll" separately:

image

The PDFs with the a password configured should now be present in the destination folder:

image

I found that the script the author provided didn’t really match the formatting I wanted for the PowerShell output and spreadsheet (my use case had nothing to do with contract numbers and date of birth) so I’ll be making modifications to it and writing another blog post for it.