Skip to content

Instantly share code, notes, and snippets.

@nickadam
Last active November 3, 2023 13:52
Show Gist options
  • Save nickadam/5a3ad649e31176b0cf5923e294a9ad60 to your computer and use it in GitHub Desktop.
Save nickadam/5a3ad649e31176b0cf5923e294a9ad60 to your computer and use it in GitHub Desktop.
Leverage CYA internals for generic encrypting or decrypting of files with a password
# Running this script will install CYA if not already installed,
# load the necessary functions from the private modules directory,
# and finally creates three sample files in the current working directory.
# Install CYA if not installed
if (-not (Get-Module -ListAvailable -Name CYA)) {
Install-Module CYA -Repository PSGallery
}
# Load CYA's private functions from the Modules directory
$env:PSModulePath -Split ";" | ForEach-Object {
$CYAPath = Join-Path $_ "CYA"
if (Test-Path $CYAPath) {
$CYAPrivatePath = Join-Path (Get-ChildItem -Directory $CYAPath | Select-Object -First 1 | Select-Object -ExpandProperty FullName) "Private"
. (Join-Path $CYAPrivatePath "ConvertFrom-EncryptedBin.ps1")
. (Join-Path $CYAPrivatePath "ConvertTo-EncryptedBin.ps1")
. (Join-Path $CYAPrivatePath "ConvertFrom-MemoryStream.ps1")
. (Join-Path $CYAPrivatePath "ConvertTo-MemoryStream.ps1")
}
}
# IMPORTANT: FileIn and FileOut must be a full path, not relative
$CWD = (Get-Location).Path
$StartingFile = Join-Path $CWD "test-file.txt"
$EncryptedFile = Join-Path $CWD "test-file.enc"
$DecryptedFile = Join-Path $CWD "test-file-decrypted.txt"
$Password = "badpassword"
# Write a test file
"This is a secret, shhh" | Out-File -Encoding Default $StartingFile
# Encrypt test file
ConvertTo-EncryptedBin -FileIn $StartingFile -FileOut $EncryptedFile -Key $Password
# Decrypt encrypted file
# ConvertFrom-EncryptedBin returns an int, ignore it with Out-Null
ConvertFrom-EncryptedBin -FileIn $EncryptedFile -FileOut $DecryptedFile -Key $Password | Out-Null
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment