Skip to content

Instantly share code, notes, and snippets.

@heaths
Last active March 30, 2022 17:21
Show Gist options
  • Save heaths/590cb9818e88da5bdf7914c28f3d3221 to your computer and use it in GitHub Desktop.
Save heaths/590cb9818e88da5bdf7914c28f3d3221 to your computer and use it in GitHub Desktop.
Use Windows DPAPI to secure files
#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