Updated both files

This commit is contained in:
Markus Fleschutz 2021-01-04 10:37:14 +01:00
parent 7641b29e7c
commit b1abddf94f
2 changed files with 21 additions and 85 deletions

View File

@ -8,9 +8,8 @@
param([string]$Path = "", [string]$Password = "") param([string]$Path = "", [string]$Password = "")
Set-StrictMode -Version Latest
Function Unprotect-File function DecryptFile
{ {
<# <#
.SYNOPSIS .SYNOPSIS
@ -42,22 +41,6 @@ Removes the source (encrypted) file after decrypting.
.OUTPUTS .OUTPUTS
System.IO.FileInfo. Unprotect-File will return FileInfo with the SourceFile as an added NoteProperty System.IO.FileInfo. Unprotect-File will return FileInfo with the SourceFile as an added NoteProperty
.EXAMPLE
Unprotect-File 'C:\secrets.txt.AES' $key
This example decrypts C:\secrets.txt.AES using the key stored in the variable $key. The decrypted file would remove the default extension of '.AES' and the source (encrypted) file would not be removed.
.EXAMPLE
Unprotect-File 'C:\secrets.txt.Encrypted' -Algorithm DES -Key $key -Suffix '.Encrypted' -RemoveSource
This example decrypts C:\secrets.txt.Encrypted using DES and the key stored in the variable $key. The decrypted file would remove the extension of '.Encrypted' and the source (encrypted) file would be removed.
.EXAMPLE
Get-ChildItem 'C:\Files' -Recurse | Unprotect-File -Algorithm AES -Key $key -RemoveSource
This example decrypts all of the files under the C:\Files directory using the key stored in the variable $key. The decrypted files would remove the default extension of '.AES' and the source (encrypted) files would be removed.
.NOTES
Author: Tyler Siegrist
Date: 9/22/2017
#> #>
[CmdletBinding(DefaultParameterSetName='SecureString')] [CmdletBinding(DefaultParameterSetName='SecureString')]
[OutputType([System.IO.FileInfo[]])] [OutputType([System.IO.FileInfo[]])]
@ -77,13 +60,12 @@ Param(
[Parameter(Mandatory=$false, Position=5, ValueFromPipelineByPropertyName=$true)] [Parameter(Mandatory=$false, Position=5, ValueFromPipelineByPropertyName=$true)]
[System.Security.Cryptography.PaddingMode]$PaddingMode = 'PKCS7', [System.Security.Cryptography.PaddingMode]$PaddingMode = 'PKCS7',
[Parameter(Mandatory=$false, Position=6)] [Parameter(Mandatory=$false, Position=6)]
[String]$Suffix, #Assigning default value in code due to it not processing ".$Algorithm" properly when Algorithm is ValueFromPipelineByPropertyName [String]$Suffix,
[Parameter()] [Parameter()]
[Switch]$RemoveSource [Switch]$RemoveSource
) )
Process Process
{ {
#Configure cryptography
try try
{ {
if($PSCmdlet.ParameterSetName -eq 'PlainText') if($PSCmdlet.ParameterSetName -eq 'PlainText')
@ -91,7 +73,6 @@ Param(
$Key = $KeyAsPlainText | ConvertTo-SecureString -AsPlainText -Force $Key = $KeyAsPlainText | ConvertTo-SecureString -AsPlainText -Force
} }
#Decrypt cryptography Key from SecureString
$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($Key) $BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($Key)
$EncryptionKey = [System.Convert]::FromBase64String([System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)) $EncryptionKey = [System.Convert]::FromBase64String([System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR))
@ -111,12 +92,10 @@ Param(
$Suffix = ".$Algorithm" $Suffix = ".$Algorithm"
} }
#Used to store successfully decrypted file names.
$Files = Get-Item -LiteralPath $FileName $Files = Get-Item -LiteralPath $FileName
ForEach($File in $Files) ForEach($File in $Files)
{ {
#Verify file ends with supplied suffix
If(-not $File.Name.EndsWith($Suffix)) If(-not $File.Name.EndsWith($Suffix))
{ {
Write-Error "$($File.FullName) does not have an extension of '$Suffix'." Write-Error "$($File.FullName) does not have an extension of '$Suffix'."
@ -130,7 +109,6 @@ Param(
$FileStreamReader = New-Object System.IO.FileStream($File.FullName, [System.IO.FileMode]::Open) $FileStreamReader = New-Object System.IO.FileStream($File.FullName, [System.IO.FileMode]::Open)
$FileStreamWriter = New-Object System.IO.FileStream($DestinationFile, [System.IO.FileMode]::Create) $FileStreamWriter = New-Object System.IO.FileStream($DestinationFile, [System.IO.FileMode]::Create)
#Get IV from file
[Byte[]]$LenIV = New-Object Byte[] 4 [Byte[]]$LenIV = New-Object Byte[] 4
$FileStreamReader.Seek(0, [System.IO.SeekOrigin]::Begin) | Out-Null $FileStreamReader.Seek(0, [System.IO.SeekOrigin]::Begin) | Out-Null
$FileStreamReader.Read($LenIV, 0, 3) | Out-Null $FileStreamReader.Read($LenIV, 0, 3) | Out-Null
@ -140,21 +118,17 @@ Param(
$FileStreamReader.Read($IV, 0, $LIV) | Out-Null $FileStreamReader.Read($IV, 0, $LIV) | Out-Null
$Crypto.IV = $IV $Crypto.IV = $IV
#Peform Decryption
$Transform = $Crypto.CreateDecryptor() $Transform = $Crypto.CreateDecryptor()
$CryptoStream = New-Object System.Security.Cryptography.CryptoStream($FileStreamWriter, $Transform, [System.Security.Cryptography.CryptoStreamMode]::Write) $CryptoStream = New-Object System.Security.Cryptography.CryptoStream($FileStreamWriter, $Transform, [System.Security.Cryptography.CryptoStreamMode]::Write)
$FileStreamReader.CopyTo($CryptoStream) $FileStreamReader.CopyTo($CryptoStream)
#Close open files
$CryptoStream.FlushFinalBlock() $CryptoStream.FlushFinalBlock()
$CryptoStream.Close() $CryptoStream.Close()
$FileStreamReader.Close() $FileStreamReader.Close()
$FileStreamWriter.Close() $FileStreamWriter.Close()
#Delete encrypted file
if($RemoveSource){Remove-Item $File.FullName} if($RemoveSource){Remove-Item $File.FullName}
#Output decrypted file
Get-Item $DestinationFile | Add-Member MemberType NoteProperty Name SourceFile Value $File.FullName -PassThru Get-Item $DestinationFile | Add-Member MemberType NoteProperty Name SourceFile Value $File.FullName -PassThru
} }
Catch Catch
@ -162,7 +136,6 @@ Param(
Write-Error $_ Write-Error $_
If($FileStreamWriter) If($FileStreamWriter)
{ {
#Remove failed file
$FileStreamWriter.Close() $FileStreamWriter.Close()
Remove-Item -LiteralPath $DestinationFile -Force Remove-Item -LiteralPath $DestinationFile -Force
} }
@ -188,7 +161,7 @@ try {
} }
$PasswordBase64 = [System.Convert]::ToBase64String($Password) $PasswordBase64 = [System.Convert]::ToBase64String($Password)
Unprotect-File "$Path" -algorithm AES -keyAsPlainText $PasswordBase64 -removeSource DecryptFile "$Path" -algorithm AES -keyAsPlainText $PasswordBase64 -removeSource
write-output "OK." write-output "OK."
exit 0 exit 0
} catch { } catch {

View File

@ -8,9 +8,7 @@
param([string]$Path = "", [string]$Password = "") param([string]$Path = "", [string]$Password = "")
Set-StrictMode -Version Latest function EncryptFile
Function Protect-File
{ {
<# <#
.SYNOPSIS .SYNOPSIS
@ -42,22 +40,6 @@ Removes the source (decrypted) file after encrypting.
.OUTPUTS .OUTPUTS
System.IO.FileInfo. Protect-File will return FileInfo with the SourceFile, Algorithm, Key, CipherMode, and PaddingMode as added NoteProperties System.IO.FileInfo. Protect-File will return FileInfo with the SourceFile, Algorithm, Key, CipherMode, and PaddingMode as added NoteProperties
.EXAMPLE
Protect-File 'C:\secrets.txt' $key
This example encrypts C:\secrets.txt using the key stored in the variable $key. The encrypted file would have the default extension of '.AES' and the source (decrypted) file would not be removed.
.EXAMPLE
Protect-File 'C:\secrets.txt' -Algorithm DES -Suffix '.Encrypted' -RemoveSource
This example encrypts C:\secrets.txt with a randomly generated DES key. The encrypted file would have an extension of '.Encrypted' and the source (decrypted) file would be removed.
.EXAMPLE
Get-ChildItem 'C:\Files' -Recurse | Protect-File -Algorithm AES -Key $key -RemoveSource
This example encrypts all of the files under the C:\Files directory using the key stored in the variable $key. The encrypted files would have the default extension of '.AES' and the source (decrypted) files would be removed.
.NOTES
Author: Tyler Siegrist
Date: 9/22/2017
#> #>
[CmdletBinding(DefaultParameterSetName='SecureString')] [CmdletBinding(DefaultParameterSetName='SecureString')]
[OutputType([System.IO.FileInfo[]])] [OutputType([System.IO.FileInfo[]])]
@ -81,68 +63,55 @@ Param(
[Parameter()] [Parameter()]
[Switch]$RemoveSource [Switch]$RemoveSource
) )
Begin begin {
{ try {
#Configure cryptography if ($PSCmdlet.ParameterSetName -eq 'PlainText') {
try
{
if($PSCmdlet.ParameterSetName -eq 'PlainText')
{
$Key = $KeyAsPlainText | ConvertTo-SecureString -AsPlainText -Force $Key = $KeyAsPlainText | ConvertTo-SecureString -AsPlainText -Force
} }
#Decrypt cryptography Key from SecureString
$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($Key) $BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($Key)
$EncryptionKey = [System.Convert]::FromBase64String([System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)) $EncryptionKey = [System.Convert]::FromBase64String([System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR))
$Crypto = [System.Security.Cryptography.SymmetricAlgorithm]::Create($Algorithm) $Crypto = [System.Security.Cryptography.SymmetricAlgorithm]::Create($Algorithm)
if($PSBoundParameters.ContainsKey('CipherMode')){ if ($PSBoundParameters.ContainsKey('CipherMode')) {
$Crypto.Mode = $CipherMode $Crypto.Mode = $CipherMode
} }
if($PSBoundParameters.ContainsKey('PaddingMode')){ if ($PSBoundParameters.ContainsKey('PaddingMode')) {
$Crypto.Padding = $PaddingMode $Crypto.Padding = $PaddingMode
} }
$Crypto.KeySize = $EncryptionKey.Length*8 $Crypto.KeySize = $EncryptionKey.Length*8
$Crypto.Key = $EncryptionKey $Crypto.Key = $EncryptionKey
} } catch {
Catch
{
Write-Error $_ -ErrorAction Stop Write-Error $_ -ErrorAction Stop
} }
} }
Process process {
{
$Files = Get-Item -LiteralPath $FileName $Files = Get-Item -LiteralPath $FileName
ForEach($File in $Files) foreach($File in $Files) {
{
$DestinationFile = $File.FullName + $Suffix $DestinationFile = $File.FullName + $Suffix
Try try {
{
$FileStreamReader = New-Object System.IO.FileStream($File.FullName, [System.IO.FileMode]::Open) $FileStreamReader = New-Object System.IO.FileStream($File.FullName, [System.IO.FileMode]::Open)
$FileStreamWriter = New-Object System.IO.FileStream($DestinationFile, [System.IO.FileMode]::Create) $FileStreamWriter = New-Object System.IO.FileStream($DestinationFile, [System.IO.FileMode]::Create)
#Write IV (initialization-vector) length & IV to encrypted file
$Crypto.GenerateIV() $Crypto.GenerateIV()
$FileStreamWriter.Write([System.BitConverter]::GetBytes($Crypto.IV.Length), 0, 4) $FileStreamWriter.Write([System.BitConverter]::GetBytes($Crypto.IV.Length), 0, 4)
$FileStreamWriter.Write($Crypto.IV, 0, $Crypto.IV.Length) $FileStreamWriter.Write($Crypto.IV, 0, $Crypto.IV.Length)
#Perform encryption
$Transform = $Crypto.CreateEncryptor() $Transform = $Crypto.CreateEncryptor()
$CryptoStream = New-Object System.Security.Cryptography.CryptoStream($FileStreamWriter, $Transform, [System.Security.Cryptography.CryptoStreamMode]::Write) $CryptoStream = New-Object System.Security.Cryptography.CryptoStream($FileStreamWriter, $Transform, [System.Security.Cryptography.CryptoStreamMode]::Write)
$FileStreamReader.CopyTo($CryptoStream) $FileStreamReader.CopyTo($CryptoStream)
#Close open files
$CryptoStream.FlushFinalBlock() $CryptoStream.FlushFinalBlock()
$CryptoStream.Close() $CryptoStream.Close()
$FileStreamReader.Close() $FileStreamReader.Close()
$FileStreamWriter.Close() $FileStreamWriter.Close()
#Delete unencrypted file if ($RemoveSource) {
if($RemoveSource){Remove-Item -LiteralPath $File.FullName} Remove-Item -LiteralPath $File.FullName
}
#Output ecrypted file
$result = Get-Item $DestinationFile $result = Get-Item $DestinationFile
$result | Add-Member MemberType NoteProperty Name SourceFile Value $File.FullName $result | Add-Member MemberType NoteProperty Name SourceFile Value $File.FullName
$result | Add-Member MemberType NoteProperty Name Algorithm Value $Algorithm $result | Add-Member MemberType NoteProperty Name Algorithm Value $Algorithm
@ -150,20 +119,14 @@ Param(
$result | Add-Member MemberType NoteProperty Name CipherMode Value $Crypto.Mode $result | Add-Member MemberType NoteProperty Name CipherMode Value $Crypto.Mode
$result | Add-Member MemberType NoteProperty Name PaddingMode Value $Crypto.Padding $result | Add-Member MemberType NoteProperty Name PaddingMode Value $Crypto.Padding
$result $result
} } catch {
Catch
{
Write-Error $_ Write-Error $_
If($FileStreamWriter) if ($FileStreamWriter) {
{
#Remove failed file
$FileStreamWriter.Close() $FileStreamWriter.Close()
Remove-Item -LiteralPath $DestinationFile -Force Remove-Item -LiteralPath $DestinationFile -Force
} }
Continue continue
} } finally {
Finally
{
if($CryptoStream){$CryptoStream.Close()} if($CryptoStream){$CryptoStream.Close()}
if($FileStreamReader){$FileStreamReader.Close()} if($FileStreamReader){$FileStreamReader.Close()}
if($FileStreamWriter){$FileStreamWriter.Close()} if($FileStreamWriter){$FileStreamWriter.Close()}
@ -182,7 +145,7 @@ try {
} }
$PasswordBase64 = [System.Convert]::ToBase64String($Password) $PasswordBase64 = [System.Convert]::ToBase64String($Password)
Protect-File "$Path" -Algorithm AES -KeyAsPlainText $PasswordBase64 -RemoveSource EnryptFile "$Path" -Algorithm AES -KeyAsPlainText $PasswordBase64 -RemoveSource
write-output "OK." write-output "OK."
exit 0 exit 0
} catch { } catch {