-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUnprotect-PathWithPassword.ps1
More file actions
501 lines (428 loc) · 20.3 KB
/
Copy pathUnprotect-PathWithPassword.ps1
File metadata and controls
501 lines (428 loc) · 20.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
function Unprotect-PathWithPassword
{
<#
.SYNOPSIS
Decrypts files that were encrypted with Protect-PathWithPassword.
.DESCRIPTION
This function decrypts files that were encrypted using AES-256-CBC encryption with PBKDF2 key derivation.
Restores original files from .enc encrypted files or processes entire directory structures.
Compatible with files encrypted by Protect-PathWithPassword and uses the same cryptographic parameters.
DECRYPTION DETAILS:
- Reads encrypted file format: [Salt:32][IV:16][EncryptedData:Variable]
- Uses AES-256-CBC decryption with the same PBKDF2 parameters as encryption
- Validates 8-byte magic header 'PWDPROT1' to detect wrong passwords reliably
- Detects file corruption and authentication failures
- Automatically removes .enc extension to restore original filenames
CROSS-PLATFORM COMPATIBILITY: This function works on PowerShell 5.1+ across Windows, macOS, and Linux
by using .NET cryptographic classes for maximum portability.
ALIASES:
The 'decrypt' alias is created only if it doesn't already exist in the current environment.
.PARAMETER Path
The encrypted file or directory path to decrypt. Accepts both relative and absolute paths.
For files: Should typically have .enc extension (but not required).
For directories: Automatically finds and processes all .enc files.
Supports pipeline input from Get-ChildItem and other cmdlets.
.PARAMETER Password
SecureString containing the decryption password. Must match the password used for encryption.
If not provided, prompts securely for the password.
Wrong passwords will result in decryption failure with appropriate error messages.
.PARAMETER OutputPath
Optional output directory or file path for decrypted files.
If not specified, removes .enc extension and creates files in the same location.
For directories, creates decrypted files in the specified output directory.
.PARAMETER Recurse
When decrypting directories, recursively decrypt all .enc files in subdirectories.
Without this switch, only .enc files in the root directory are processed.
.PARAMETER Force
Overwrite existing decrypted files without prompting for confirmation.
Use with caution as this will replace existing files.
.PARAMETER KeepEncrypted
Keep the original encrypted .enc files after successful decryption.
By default, encrypted files are removed after successful decryption.
Use this option to maintain backup copies of encrypted files.
.EXAMPLE
PS > Unprotect-PathWithPassword -Path "C:\Documents\secret.txt.enc"
Decrypts a single file, prompting for password. Creates secret.txt and removes secret.txt.enc.
.EXAMPLE
PS > $password = Read-Host -AsSecureString -Prompt "Enter decryption password"
PS > Unprotect-PathWithPassword -Path "C:\Documents\secret.txt.enc" -Password $password
Decrypts a single file with a pre-entered password.
.EXAMPLE
PS > Unprotect-PathWithPassword -Path "C:\Encrypted" -Recurse -KeepEncrypted
Recursively decrypts all .enc files in the Encrypted directory, keeping the original encrypted files.
.EXAMPLE
PS > Get-ChildItem "*.enc" | Unprotect-PathWithPassword -Password $password
Decrypts all .enc files in current directory via pipeline.
.EXAMPLE
PS > Unprotect-PathWithPassword -Path "C:\Encrypted" -OutputPath "C:\Decrypted" -Recurse -Force
Decrypts all .enc files from C:\Encrypted recursively, placing decrypted files in C:\Decrypted.
.EXAMPLE
PS > Unprotect-PathWithPassword -Path "/home/user/encrypted" -Recurse
Linux/macOS example: Decrypts all .enc files in the encrypted directory recursively.
.EXAMPLE
# Cross-platform workflow: Files encrypted on any platform can be decrypted on any other
# Encrypted on macOS:
PS > Protect-PathWithPassword -Path "~/documents/secret.txt"
# Transfer secret.txt.enc to Windows, then decrypt:
PS > Unprotect-PathWithPassword -Path "C:\Users\user\Downloads\secret.txt.enc"
The same PowerShell functions work identically across Windows, macOS, and Linux.
.EXAMPLE
# OpenSSL-compatible decryption (bash/zsh) - requires OpenSSL 3.0+ with KDF support:
./Tests/Integration/Security/scripts/pwsh-encrypt-compat.sh decrypt -i secret.txt.enc -o secret.txt -p "MyPassword123"
# Files encrypted by PowerShell can be decrypted using the provided bash script:
# This allows decryption on systems where PowerShell may not be available.
See Tests/Integration/Security/scripts/pwsh-encrypt-compat.sh for full implementation details.
.EXAMPLE
PS > $password = ConvertTo-SecureString $env:BUILD_SECRET -AsPlainText -Force
PS > Unprotect-PathWithPassword -Path './artifacts/app.zip.enc' -Password $password -OutputPath './staging/app.zip'
PS > Expand-Archive './staging/app.zip' -DestinationPath './dist'
Release pipeline example: decrypts an encrypted artifact using a CI secret and unpacks it for deployment.
.EXAMPLE
PS > $password = Read-Host -AsSecureString -Prompt 'Enter vault password'
PS > Get-ChildItem './secure-config/*.enc' | Unprotect-PathWithPassword -Password $password -OutputPath './config' -Force -KeepEncrypted
Restores multiple encrypted configuration files before running local integration tests, keeping the encrypted originals for later reuse.
.OUTPUTS
System.Management.Automation.PSCustomObject
Returns objects with EncryptedPath, DecryptedPath, Success, and Error properties for each processed file.
.NOTES
SECURITY:
Provides secure password verification and detects file corruption or tampering.
Failed decryption attempts do not create partial files.
COMPATIBILITY:
Requires .NET Framework 4.0+ or .NET Core 2.0+ for cryptographic functions.
Files encrypted on any platform can be decrypted on any other platform running PowerShell.
OPENSSL COMPATIBILITY:
OpenSSL's 'enc' command uses a different file format and is NOT directly compatible.
However, OpenSSL can be used to create and decrypt compatible files using lower-level commands.
A reference bash script (Tests/Integration/Security/scripts/pwsh-encrypt-compat.sh) demonstrates how to use
OpenSSL's 'kdf' command for PBKDF2 key derivation and 'enc' with explicit -K/-iv flags
to encrypt/decrypt files in the same format as these PowerShell functions.
This enables encryption/decryption on systems without PowerShell using only OpenSSL.
ERROR HANDLING:
Distinguishes between wrong passwords, corrupted files, and other errors.
CLEANUP:
Encrypted files are only removed after successful decryption unless -KeepEncrypted is specified.
Author: Jon LaBelle
License: MIT
Source: https://github.com/jonlabelle/pwsh-profile/blob/main/Functions/Security/Unprotect-PathWithPassword.ps1
.LINK
https://github.com/jonlabelle/pwsh-profile/blob/main/Functions/Security/Unprotect-PathWithPassword.ps1
#>
[CmdletBinding(SupportsShouldProcess)]
[OutputType([PSCustomObject])]
param(
[Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName)]
[Alias('FullName')]
[ValidateScript({
$normalizedPath = $PSCmdlet.SessionState.Path.GetUnresolvedProviderPathFromPSPath($_)
if (-not (Test-Path $normalizedPath))
{
throw "Path does not exist: $normalizedPath"
}
$true
})]
[String]$Path,
[Parameter()]
[ValidateNotNull()]
[SecureString]$Password,
[Parameter()]
[String]$OutputPath,
[Parameter()]
[Switch]$Recurse,
[Parameter()]
[Switch]$Force,
[Parameter()]
[Switch]$KeepEncrypted
)
begin
{
Write-Verbose 'Starting decryption process'
# Validate .NET encryption support
try
{
Add-Type -AssemblyName System.Security -ErrorAction Stop
}
catch
{
throw 'System.Security assembly not available. Decryption requires .NET Framework 4.0+ or .NET Core 2.0+'
}
# Get password if not provided
if (-not $Password)
{
Write-Host 'Enter decryption password:' -ForegroundColor Yellow
$Password = Read-Host -AsSecureString
}
# Resolve output path if provided
if ($OutputPath)
{
# Expand '~', resolve relative paths, and convert to absolute path
$OutputPath = $PSCmdlet.SessionState.Path.GetUnresolvedProviderPathFromPSPath($OutputPath)
# Create output directory if it doesn't exist and it looks like a directory
if (-not (Test-Path $OutputPath))
{
# Check if this looks like a directory (no extension or ends with slash/backslash)
$isDirectory = (-not [System.IO.Path]::HasExtension($OutputPath)) -or
$OutputPath.EndsWith('/') -or
$OutputPath.EndsWith('\')
if ($isDirectory)
{
try
{
New-Item -Path $OutputPath -ItemType Directory -Force | Out-Null
Write-Verbose "Created output directory: $OutputPath"
}
catch
{
throw "Failed to create output directory: $OutputPath"
}
}
else
{
# It's a file path, so create the parent directory if needed
$parentDir = [System.IO.Path]::GetDirectoryName($OutputPath)
if ($parentDir -and -not (Test-Path $parentDir))
{
try
{
New-Item -Path $parentDir -ItemType Directory -Force | Out-Null
Write-Verbose "Created parent directory: $parentDir"
}
catch
{
throw "Failed to create parent directory: $parentDir"
}
}
}
}
}
# Internal helper function for file decryption
function Invoke-FileDecryption
{
[CmdletBinding(SupportsShouldProcess)]
param(
[String]$FilePath,
[SecureString]$Password,
[String]$OutputPath,
[Switch]$Force,
[Switch]$KeepEncrypted
)
try
{
# Determine output file path
if ($OutputPath)
{
if (Test-Path $OutputPath -PathType Container)
{
$fileName = [System.IO.Path]::GetFileName($FilePath)
if ($fileName.EndsWith('.enc'))
{
$fileName = $fileName.Substring(0, $fileName.Length - 4)
}
$outputFile = Join-Path -Path $OutputPath -ChildPath $fileName
}
else
{
$outputFile = $OutputPath
}
}
else
{
if ($FilePath.EndsWith('.enc'))
{
$outputFile = $FilePath.Substring(0, $FilePath.Length - 4)
}
else
{
$outputFile = $FilePath + '.dec'
}
}
# Check if output file exists
if ((Test-Path $outputFile) -and -not $Force)
{
Write-Warning "Skipping file: $FilePath (file exists, use -Force to overwrite)"
return [PSCustomObject]@{
EncryptedPath = $FilePath
DecryptedPath = $outputFile
Success = $false
Error = 'File exists and Force not specified'
}
}
if ($PSCmdlet.ShouldProcess($FilePath, 'Decrypt file'))
{
# Convert SecureString to bytes for key derivation
$passwordPtr = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($Password)
try
{
$passwordPlain = [System.Runtime.InteropServices.Marshal]::PtrToStringBSTR($passwordPtr)
$passwordBytes = [System.Text.Encoding]::UTF8.GetBytes($passwordPlain)
}
finally
{
[System.Runtime.InteropServices.Marshal]::ZeroFreeBSTR($passwordPtr)
if ($passwordPlain)
{
$passwordPlain = $null
}
}
# Read encrypted file
$encryptedData = [System.IO.File]::ReadAllBytes($FilePath)
# Validate minimum file size (32 bytes salt + 16 bytes IV + at least 16 bytes data)
if ($encryptedData.Length -lt 64)
{
throw 'Invalid encrypted file format: file too small'
}
# Extract salt, IV, and encrypted data
$salt = $encryptedData[0..31]
$initializationVector = $encryptedData[32..47]
$encryptedBytes = $encryptedData[48..($encryptedData.Length - 1)]
# Derive key using PBKDF2 (same parameters as encryption)
$pbkdf2 = New-Object System.Security.Cryptography.Rfc2898DeriveBytes($passwordBytes, $salt, 100000, [System.Security.Cryptography.HashAlgorithmName]::SHA256)
$key = $pbkdf2.GetBytes(32) # 256-bit key
$pbkdf2.Dispose()
# Clear password bytes
[Array]::Clear($passwordBytes, 0, $passwordBytes.Length)
# Decrypt using AES
$aes = [System.Security.Cryptography.Aes]::Create()
$aes.Key = $key
$aes.IV = $initializationVector
$aes.Mode = [System.Security.Cryptography.CipherMode]::CBC
$aes.Padding = [System.Security.Cryptography.PaddingMode]::PKCS7
try
{
$decryptor = $aes.CreateDecryptor()
$decryptedBytes = $decryptor.TransformFinalBlock($encryptedBytes, 0, $encryptedBytes.Length)
$decryptor.Dispose()
}
catch
{
throw 'Decryption failed. Invalid password or corrupted file.'
}
finally
{
$aes.Dispose()
[Array]::Clear($key, 0, $key.Length)
}
# Validate magic header (8 bytes: PWDPROT1)
if ($decryptedBytes.Length -lt 8)
{
throw 'Decryption failed. Invalid password or corrupted file.'
}
$magicHeader = [System.Text.Encoding]::ASCII.GetBytes('PWDPROT1')
$headerMatch = $true
for ($i = 0; $i -lt 8; $i++)
{
if ($decryptedBytes[$i] -ne $magicHeader[$i])
{
$headerMatch = $false
break
}
}
if (-not $headerMatch)
{
throw 'Decryption failed. Invalid password or corrupted file.'
}
# Remove magic header from decrypted data
$actualData = New-Object byte[] ($decryptedBytes.Length - 8)
[System.Buffer]::BlockCopy($decryptedBytes, 8, $actualData, 0, $actualData.Length)
# Write decrypted file
[System.IO.File]::WriteAllBytes($outputFile, $actualData)
# Remove encrypted file if requested
if (-not $KeepEncrypted)
{
Remove-Item -Path $FilePath -Force
Write-Verbose "Removed encrypted file: $FilePath"
}
Write-Verbose "Successfully decrypted '$FilePath' to '$outputFile'"
[PSCustomObject]@{
EncryptedPath = $FilePath
DecryptedPath = $outputFile
Success = $true
Error = $null
}
}
else
{
# WhatIf - return what would happen
[PSCustomObject]@{
EncryptedPath = $FilePath
DecryptedPath = $outputFile
Success = $true
Error = $null
}
}
}
catch
{
Write-Error "Failed to decrypt file '$FilePath': $($_.Exception.Message)"
[PSCustomObject]@{
EncryptedPath = $FilePath
DecryptedPath = $outputFile
Success = $false
Error = $_.Exception.Message
}
}
}
}
process
{
try
{
# Normalize path first (handles ~, relative paths)
$Path = $PSCmdlet.SessionState.Path.GetUnresolvedProviderPathFromPSPath($Path)
# Then validate existence
$resolvedPath = Resolve-Path -Path $Path -ErrorAction Stop
$item = Get-Item -Path $resolvedPath -ErrorAction Stop
if ($item.PSIsContainer)
{
Write-Verbose "Processing directory: $($item.FullName)"
if ($Recurse)
{
Get-ChildItem -Path $item.FullName -File -Filter '*.enc' -Recurse | ForEach-Object {
$result = Invoke-FileDecryption -FilePath $_.FullName -Password $Password -OutputPath $OutputPath -Force:$Force -KeepEncrypted:$KeepEncrypted
Write-Output $result
}
}
else
{
Get-ChildItem -Path $item.FullName -File -Filter '*.enc' | ForEach-Object {
$result = Invoke-FileDecryption -FilePath $_.FullName -Password $Password -OutputPath $OutputPath -Force:$Force -KeepEncrypted:$KeepEncrypted
Write-Output $result
}
}
}
else
{
Write-Verbose "Processing file: $($item.FullName)"
$result = Invoke-FileDecryption -FilePath $item.FullName -Password $Password -OutputPath $OutputPath -Force:$Force -KeepEncrypted:$KeepEncrypted
Write-Output $result
}
}
catch
{
Write-Error "Failed to process path '$Path': $($_.Exception.Message)"
[PSCustomObject]@{
EncryptedPath = $Path
DecryptedPath = $null
Success = $false
Error = $_.Exception.Message
}
}
}
end
{
Write-Verbose 'Decryption process completed'
}
}
# Create 'decrypt' alias only if it doesn't already exist
if (-not (Get-Command -Name 'decrypt' -ErrorAction SilentlyContinue))
{
try
{
Write-Verbose "Creating 'decrypt' alias for Unprotect-PathWithPassword"
Set-Alias -Name 'decrypt' -Value 'Unprotect-PathWithPassword' -Force -ErrorAction Stop
}
catch
{
Write-Warning "Unprotect-PathWithPassword: Could not create 'decrypt' alias: $($_.Exception.Message)"
}
}