Skip to content

Instantly share code, notes, and snippets.

@itsho
Last active November 17, 2021 22:00
Show Gist options
  • Save itsho/9d2cc17de32b45de08457ad099fcd7ec to your computer and use it in GitHub Desktop.
Save itsho/9d2cc17de32b45de08457ad099fcd7ec to your computer and use it in GitHub Desktop.
Encrypt folder with GnuPG
Write-Host "Encrypt folder with GnuPG."
Write-Host "Itamar 2021-11-17"
$gpgExeLocaiton = "C:\Program Files (x86)\GnuPG\bin\gpg.exe"
$inputFolder = "C:\Temp\origin"
$outputFolder = "C:\temp\output"
$recipientEmail = "[email protected]"
if ([string]::IsNullOrEmpty("$inputFolder") -or -not (Test-Path -Path "$inputFolder" -PathType Container)){
Write-Error "input folder does not exist."
exit 1
}
if ([string]::IsNullOrEmpty("$outputFolder")){
Write-Error "output folder must be selected."
exit 1
}
# will check that the output folder exist. if not, it will create it.
New-Item -Path "$outputFolder" -ItemType "directory" -Force
if ([string]::IsNullOrEmpty("$gpgExeLocaiton") -or -not (Test-Path -Path "$gpgExeLocaiton" -PathType Leaf)){
Write-Error "gpg exe does not exist. please install GnuPG for windows from here https://gnupg.org/download/ and set the correct path"
exit 1
}
if ([string]::IsNullOrEmpty("$recipientEmail")){
Write-Error "you must specify email for pubkey stored within local storage of GnuPG"
exit 1
}
Write-Host "Checking if email pubkey is stored locally..."
$keysList = & "$gpgExeLocaiton" --list-keys
$foundValidEmail = $false
foreach ($line in $keysList){
if ($line.Contains($recipientEmail)){
$foundValidEmail = $true
break;
}
}
if (-not $foundValidEmail){
Write-Error "The email $recipientEmail is not part of the stored certs in GnuPG:`r`n$pubring"
exit 1
}else {
Write-Host "Email '$recipientEmail' is stored locally."
}
Write-Host "Loading folder '$inputFolder' content..."
$listOfFiles = Get-ChildItem "$inputFolder" -Recurse -Exclude "*.gpg"
Write-Host "Found $($inputFolder.Length) files to encrypt..."
foreach ($fileToSign in $listOfFiles){
Write-Host "About to encrypt '$fileToSign' with email '$recipientEmail'..."
$targetFile = [System.IO.Path]::Combine($outputFolder,"$($fileToSign.Name).gpg")
if (test-path "$targetFile") {
Write-Host "Removing old GPG file: '$targetFile'"
Remove-Item -Path "$targetFile" -Force
}
& "$gpgExeLocaiton" --output "$targetFile" --encrypt --recipient "$recipientEmail" "$($fileToSign.FullName)"
if ($LASTEXITCODE -ne 0) {
Write-Error "Failed to encrypt '$fileToSign' exit code: $LASTEXITCODE"
exit 1
}
Write-Host "File '$fileToSign' encrypted to '$targetFile' successfully`r`n"
}
Write-Host "Done."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment