Last active
March 30, 2022 17:21
-
-
Save heaths/590cb9818e88da5bdf7914c28f3d3221 to your computer and use it in GitHub Desktop.
Use Windows DPAPI to secure files
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#Requires -Version 5.0 | |
function Protect-SecureFile { | |
[CmdletBinding(DefaultParameterSetName = 'Path')] | |
param ( | |
[Parameter(ParameterSetName = 'Path', Mandatory = $true, Position = 0, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] | |
[string] $Path, | |
[Parameter(ParameterSetName = 'LiteralPath', Mandatory = $true, ValueFromPipelineByPropertyName = $true)] | |
[Alias('PSPath')] | |
[string] $LiteralPath, | |
[Parameter(Mandatory = $true, Position = 1)] | |
[string] $Destination, | |
[Parameter()] | |
[ValidateNotNullOrEmpty()] | |
[byte[]] $Entropy, | |
[Parameter()] | |
[ValidateSet('CurrentUser', 'LocalMachine')] | |
[string] $Scope = 'CurrentUser', | |
[Parameter()] | |
[switch] $Force, | |
[Parameter()] | |
[switch] $NoRemove | |
) | |
if ($PSCmdlet.ParameterSetName -eq 'Path') { | |
$LiteralPath = Resolve-Path $Path | |
} | |
$buffer = Get-Content -LiteralPath $LiteralPath -AsByteStream | |
[System.Security.Cryptography.ProtectedData]::Protect($buffer, $Entropy, $Scope) | Set-Content -Path $Destination -AsByteStream -Force:$Force | |
if (!$NoRemove) { | |
# Always force to protect unsecured source. | |
Remove-Item -LiteralPath $LiteralPath -Force | |
} | |
} | |
function Unprotect-SecureFile { | |
[CmdletBinding(DefaultParameterSetName = 'Path')] | |
param ( | |
[Parameter(ParameterSetName = 'Path', Mandatory = $true, Position = 0, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] | |
[string] $Path, | |
[Parameter(ParameterSetName = 'LiteralPath', Mandatory = $true, ValueFromPipelineByPropertyName = $true)] | |
[Alias('PSPath')] | |
[string] $LiteralPath, | |
[Parameter(Mandatory = $true, Position = 1)] | |
[string] $Destination, | |
[Parameter()] | |
[ValidateNotNullOrEmpty()] | |
[byte[]] $Entropy, | |
[Parameter()] | |
[ValidateSet('CurrentUser', 'LocalMachine')] | |
[string] $Scope = 'CurrentUser' | |
[Parameter()] | |
[switch] $Force, | |
) | |
if ($PSCmdlet.ParameterSetName -eq 'Path') { | |
$LiteralPath = Resolve-Path $Path | |
} | |
$buffer = Get-Content -LiteralPath $LiteralPath -AsByteStream | |
[System.Security.Cryptography.ProtectedData]::Unprotect($buffer, $Entropy, $Scope) | Set-Content -Path $Destination -AsByteStream -Force:$Force | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment