Coder Social home page Coder Social logo

evotecit / pspgp Goto Github PK

View Code? Open in Web Editor NEW
55.0 6.0 21.0 6.16 MB

PSPGP is a PowerShell module that provides PGP functionality in PowerShell. It allows encrypting and decrypting files/folders and strings using PGP.

License: MIT License

PowerShell 96.17% C# 3.83%
powershell pgp gpg

pspgp's Introduction

PSPGP - PowerShell Module

PSPGP is a PowerShell module that provides PGP functionality in PowerShell. It allows encrypting and decrypting files/folders and strings using PGP. PSGPG uses following .NET library to deliver this functionality:

To install

Install-Module -Name PSPGP -AllowClobber -Force

Force and AllowClobber aren't necessary, but they do skip errors in case some appear.

And to update

Update-Module -Name PSPGP

That's it. Whenever there's a new version, you run the command, and you can enjoy it. Remember that you may need to close, reopen PowerShell session if you have already used module before updating it.

The essential thing is if something works for you on production, keep using it till you test the new version on a test computer. I do changes that may not be big, but big enough that auto-update may break your code. For example, a small rename to a parameter, and your code stops working! Be responsible!

IMPORTANT

This module works correctly on Windows/Linux and MacOS, but since it uses .NET STANDARD 2.0 library it requires minimum of .NET Framework 4.7.2 installed on a Windows machine when using PowerShell 5.1. Please make sure to keep your .NET Framework up to date on Windows Client/Servers.

Using

Create new PGP Public/Private Keys

New-PGPKey -FilePathPublic $PSScriptRoot\Keys\PublicPGP.asc -FilePathPrivate $PSScriptRoot\Keys\PrivatePGP.asc -UserName 'przemyslaw.klys' -Password 'ZielonaMila9!'

Encrypt Folder

Protect-PGP -FilePathPublic $PSScriptRoot\Keys\PublicPGP.asc -FolderPath $PSScriptRoot\Test -OutputFolderPath $PSScriptRoot\Encoded

Decrypt Folder

Unprotect-PGP -FilePathPrivate $PSScriptRoot\Keys\PrivatePGP.asc -Password 'ZielonaMila9!' -FolderPath $PSScriptRoot\Encoded -OutputFolderPath $PSScriptRoot\Decoded

Encrypt / Decrypt String

$ProtectedString = Protect-PGP -FilePathPublic $PSScriptRoot\Keys\PublicPGP.asc -String "This is string to encrypt"
Unprotect-PGP -FilePathPrivate $PSScriptRoot\Keys\PrivatePGP.asc -Password 'ZielonaMila9!' -String $ProtectedString

Verify signature

$ProtectedString = Protect-PGP -FilePathPublic $PSScriptRoot\Keys\PublicPGP.asc -String "This is string to encrypt"

Test-PGP -FilePathPublic $PSScriptRoot\Keys\PublicPGP.asc -String $ProtectedString

Test-PGP -FilePathPublic $PSScriptRoot\Keys\PublicPGP.asc -FolderPath $PSScriptRoot\Encoded

pspgp's People

Contributors

przemyslawklys avatar davegreen avatar s0up2up avatar

Stargazers

jstuedle avatar Joakim Durehed avatar Squid avatar  avatar idk avatar  avatar reidwrite avatar Christopher Conley avatar Kevin James O'Dea avatar Dr. Renard Sc.D avatar Samy Lahfa avatar Jeff Maxton avatar Jimmy Briggs avatar Furechan avatar Jorgy avatar  avatar Darren Neimke avatar Grant Kilber avatar Russell O'Connell avatar Frederik Hjorslev avatar gojj avatar  avatar  avatar  avatar Ryland avatar  avatar Helmoes avatar  avatar  avatar KBase avatar Justin avatar  avatar  avatar Maki Kato avatar fatherofinvention avatar  avatar  avatar Luca avatar Michael Johnson avatar AP avatar Dmitry Danilov avatar techris avatar  avatar  avatar  avatar Cole Lavallee avatar  avatar Byron Jones avatar  avatar  avatar Miodrag Milić avatar brock chapin avatar guoyucn avatar Dan Aickin avatar Andreas Dieckmann avatar

Watchers

James Cloos avatar idk avatar  avatar  avatar Tom avatar  avatar

pspgp's Issues

Bug using library with "Unable to find type [PgpCore.EncryptionKeys]"

I am trying to use your excellent Module, however, I seem to be encountering errors like below:

WARNING: Protect-PGP - Can't encrypt files because: Unable to find type [PgpCore.EncryptionKeys].
WARNING: Protect-PGP - Can't encrypt files because: Unable to find type [PgpCore.EncryptionKeys].

I am stuck as this doesn't seem to want to go away. I am running this on Windows Server 2016. This is the output from the $PSVersionTable

$PSVersionTable

Name                           Value                                                                                                                                                          
----                           -----                                                                                                                                                          
PSVersion                      5.1.14393.4583                                                                                                                                                 
PSEdition                      Desktop                                                                                                                                                        
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}                                                                                                                                        
BuildVersion                   10.0.14393.4583                                                                                                                                                
CLRVersion                     4.0.30319.42000                                                                                                                                                
WSManStackVersion              3.0                                                                                                                                                            
PSRemotingProtocolVersion      2.3                                                                                                                                                            
SerializationVersion           1.1.0.1

I have tried this on 2 separate Windows Server instances and am encountering the same issue. Any idea what is going on and how to work around this issue?

Encrypt to multiple public keys

Hello, while I haven't extensively tested this, I don't think it can allow encrypting to multiple public keys.
I understand it's totally do-able in PGP world - but is the script able to do this as is?
Regards

Issues encrypting file

HI,

I'm trying to encrypt a file and I am getting WARNING: Protect-PGP - Can't encrypt file C:\local\Temp\export.csv: Exception calling "EncryptFile" with "2" argument(s): "No encryption methods specified"

I am calling it this way:

Write the key text to a temporary file

$keyFilePath = Join-Path $env:TEMP "public.asc"
Set-Content -Path $keyFilePath -Value $env:gpgKey

Encrypt the CSV file

$encryptedContent = Protect-PGP -FilePathPublic $keyFilePath -FilePath $localFilePathdownload

Would love some assistance to understand why this is failing :)

Sofia

Unprotect-PGP from smb share fails

Environment

  • Windows Server 2019
  • PowerShell 5.1
  • PSPGP 0.1.9
  • Reading and writing from/to over windows file system share

It seems that performing Unprotect-PGP on a file directly over an windows file/smb share/UNC path files. But if the file is placed locally its possible to output it directly to a windows file/smb share/UNC path.

Unprotect-PGP -FilePathPrivate "C:\FILES\scripts\unprotect\gpg__privkey.asc" -Password "" -FilePath "\\domain.tld\shares\automatic\encrypted\2022-11-03.csv.pgp" -OutFilePath "\\domain.tld\shares\automatic\2022-11-03.csv.pgp"
results in

WARNING: Unprotect-PGP - Remove PGP encryption from \domain.tld\shares\automatic\encrypted\2022-11-03.csv.pgp failed: Exception calling "DecryptFile" with "4" argument(s): "Encrypted File [Microsoft.PowerShell.Core\FileSystem::\domain.tld\shares\automatic\encrypted\2022-11-03.csv.pgp] not found."

But this works fine
Unprotect-PGP -FilePathPrivate "C:\FILES\scripts\unprotect\gpg__privkey.asc" -Password "" -FilePath "C:\FILES\temp\unprotect\2022-11-03.csv.pgp" -OutFilePath "\\domain.tld\shares\automatic\2022-11-03.csv.pgp"

How to Handle errors

Hi There,
I'm using your module within a Powershell script, on of the steps in the script decrypts a file with your module. If I use the right key the file is decrypted ok and creates the file (i.e. file.txt), however, if I use the wrong key, the module does not decrypt the file but it still creates an empty output file (i.e. empty file.txt). To validate success of the decryption I'm validating that the decrypted file has been created.
Is there a way I can ask the module not to crete the empty file when it fails to decrypt the file?

Thanks for this module and your help with this issue!

Unprotect-PGP does not resolve path

When I run the parameters -FilePath or -OutputFilePath with home dir shortcut, I get the following errors:

Could not find a part of the path 'H:\~\Downloads\testoutput.zip'.
Encrypted File [~\Downloads\test.pgp] not found.

Not using resolve-path probably applies to other param sets, haven't tried them. Feel free to close as WONTFIX and comment here that relative paths can't use aliases or need to be absolute paths. Or I can submit a PR in a little bit.

Additionally, these fatal errors do not result in red test and error, so the only way to test if the command succeeded is to do a test-path on the expected output path. Would recommend a throw anytime decryption is stopped or at least a -Passthru param that will ONLY produce pipeline output on successful decryption.

Test-PGP Fails to Validate Signature But GPG4Win Can

I am having an issue testing if a gpg file has been signed. I am using PSPGP 0.1.12 Test-PGP and you can see below that the 240216 file tests valid, but the 240223 file doesn't.

FilePath                                                                                            Status Error
--------                                                                                            ------ -----
C:\source\git\CAHCO-PGPFileTransfer\src\app\download\FromKP\240216 Non-Automated Test File.docx.gpg   True
C:\source\git\CAHCO-PGPFileTransfer\src\app\download\FromKP\240223 Non-Automated Test File.docx.gpg  False

But if I open both files using gpg4win application, both are signed in the same way and show that they are validly signed

240216 Non-Automated Test File.docx.gpg
image

240223 Non-Automated Test File.docx.gpg
image

Verifying Python installer's GPG signature

I'm trying to use PSPGP to verify the signature of the Python installer, but I'm getting the following error:

Test-PGP -FilePathPublic $python_installer_win_public_key_path -FilePath $python_installer_pgp_signature_path WARNING: Test-PGP - Can't test file C:\Temp\python_test\python-3.10.5-amd64.exe.asc: Exception calling "VerifyFile" with "1" argument(s): "Object reference not set to an instance of an object."

It could be unrelated to PSPGP and due to something silly that I'm doing, since PS is not my native tongue - but I haven't been able to figure it out.


Here's the code that produces the error:

Set-PSRepository PSGallery -InstallationPolicy Trusted
Install-Module -Name PSPGP

$download_directory = "C:\Temp\python_test"
$python_installer_url = "https://www.python.org/ftp/python/3.10.5/python-3.10.5-amd64.exe"
$python_installer_pgp_signature_url = "https://www.python.org/ftp/python/3.10.5/python-3.10.5-amd64.exe.asc"
$python_installer_win_public_key_url = "https://keybase.io/stevedower/pgp_keys.asc?fingerprint=7ed10b6531d7c8e1bc296021fc624643487034e5"

$python_installer_path = $download_directory + "\" + [System.IO.Path]::GetFileName($python_installer_url)
$python_installer_pgp_signature_path = $download_directory + "\" + [System.IO.Path]::GetFileName($python_installer_pgp_signature_url)
$python_installer_win_public_key_path = $download_directory + "\" + "python_pgp_public_key.asc"

If(!(test-path -PathType container $download_directory)) {
    New-Item -ItemType Directory -Path $download_directory | Out-Null
}

Invoke-WebRequest $python_installer_url -OutFile $python_installer_path
Invoke-WebRequest $python_installer_pgp_signature_url -OutFile $python_installer_pgp_signature_path
Invoke-WebRequest $python_installer_win_public_key_url -OutFile $python_installer_win_public_key_path

Test-PGP -FilePathPublic $python_installer_win_public_key_path -FilePath $python_installer_pgp_signature_path

I can get the desired result by gpg.exe, but I'd prefer not having to include a separate step to install GPG4Win in order to verify the signature.

image


Maybe the problem is that I'm trying to verify a detached signature (as described here) - and I'm not sure if PSPGP has the capabilities to handle these?

Anyway, do you have any suggestions for me? :)

PSPGP conflicting with Az.KeyVault (4.*)

Hi,

I build a Azure Function to encrypt a file with the public key stored in Key Vault secret (base64 encoded)

Anytime, I import-module az.keyvault and pspgpg, the issue will occur as the screenshot attached.
Error Message: ERROR: Assembly with same name is already loaded

I tried different ways from Remov-Module before call a new function from PSPGP (IE: Protect-PGP), but we got the same issue. After searching around, I found that PSPGP may import some modules with Az.KeyVault, which cause conflict

Please advise if there is a work around on this

Regards

Screen Shot 2023-03-17 at 11 20 14 pm

PSPGP HashAlgorithmTag "SHA256"

Hi Przemysław Kłys, thanks so much for this great ps for pgp. Have a question of how to change HashAlgorithmTag?
As read PgpCore, the default of HashAlgorithmTag is SHA1. I want to change it using SHA256.
Any parameter of your ps or other way that can achieve it?
Thanks.

Signing files option missed

Hello Przemysław,

thank You for writing the module which made the process encrypt/decrypt of PGP files much easier for me (multiple files too, which is important to me).
As I wrote in the email one important funcionality is missing here, I mean - signing files. PGPCore supports that option.
If it's possible to add that feature - signing files,
(encrypt and sign), it will be great.

Tom

Protect-PGP exception when running in PowerShell 5.1 in Azure Automations Runbook

Hey Team,

I'm trying to use use Protect-PGP in an Azure Automations Runbook. The cmdlet runs great using the 7.1 preview Runbooks but returns the following exception on 5.1:
Protect-PGP - Can't encrypt string: Exception calling "EncryptArmoredString" with "1" argument(s): "Premature end of stream in PartialInputStream"

The docs for the Runbooks state that the sandbox where the scripts run have .NET Framework 4.7.2, so it should meet the requirements of the Module
https://docs.microsoft.com/en-us/azure/automation/automation-runbook-execution#runbook-execution-environment

The code that I'm using is very simple for testing:
Protect-PGP -FilePathPublic $KeyPath -String "This needs to be protected"

I've also attempted to test with in input file and it returned a very similar error:
Protect-PGP - Can't encrypt file C:\Users\Client\Temp\ToProtect.txt: Exception calling "EncryptFile" with "2" argument(s): "Premature end of stream in PartialInputStream"

Protect-PGP does not create an encrypted file by specifying the path with -OutFilePath

Hello,
Since version 0.1.7, I have a different behavior with the Protect-PGP command.
I use the -OutFilePath parameter to create the encrypted file in a different directory than the -FilePath to separate them.
As this is an output file, the file path does not exist yet and I get a warning message WARNING: Protect-PGP - Can't encrypt file : Cannot find path 'C:\Project\File.txt.pgp' because it does not exist.

I noticed, on line 65, the use of Resolve-Path which returns this error because the path does not exist. Usually, an output path is given for the file in order to create it so the file does not exist. I think we should remove this control or use it to add a warning that the output file already exists and that it will be rewritten asking for confirmation. In this case, add a -Force parameter to apply this change.

Here is an example with the -Force parameter and a check if the file does not already exist.

        [Parameter(Mandatory, ParameterSetName = 'File')][string] $FilePath,
        [Parameter(ParameterSetName = 'File')][string] $OutFilePath,
        [Parameter(ParameterSetName = 'File')][switch]$Force,
....
    elseif ($FilePath) {
        try {
            $ResolvedFilePath = Resolve-Path -Path $FilePath
            if ($OutFilePath) {
                $TestOutFilePath = Test-Path -Path $OutFilePath
                if ($TestOutFilePath -and -not $Force)
                {
                    Write-Warning -Message "Protect-PGP - Can't encrypt file $($File.FuleName): The file already exists. Please use -Force to overwrite."
                    return    
                }
                $PGP.EncryptFile($ResolvedFilePath.Path, "$($OutFilePath)")
            }
            else { $PGP.EncryptFile($ResolvedFilePath.Path, "$($ResolvedFilePath.Path).pgp") }
        }
        catch {
            if ($PSBoundParameters.ErrorAction -eq 'Stop') { throw } else {
                Write-Warning -Message "Protect-PGP - Can't encrypt file $($File.FuleName): $($_.Exception.Message)"
                return
            }
        }
    }

Have a nice day,
Romain

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.