Passwörter in PowerShell Skripten benutzen – Die Verschlüsselung

The estimated reading time 4 minutes

Passwortverschlüsselung mit AES256 Schlüssel

HINWEIS: bevor es los geht, solltet ihr zunächst meine Einleitung zu diesem Thema lesen PROLOG.
LINK Teil 2 Passwörter in PowerShell Skripten benutzen – Die Entschlüsselung

Weil mir Automatisierung viel Spaß macht, wollte ich ein Skript erstellen, welches zwei Dateien (einmal die Verschlüsselungsdatei und die Passwortdatei). Ich weiß, dass dies nicht die weltbeste Möglichkeit ist Passwörter abzulegen, aber auf jeden Fall besser als in Klartext innerhalb des Skriptes.
Das Skript kann mit zwei Parametern gesteuert werden:
password-store.ps1 -KeyFilePath C:\temp\aeskey.key -CredFilePath C:\temp\password.txt

DOWNLOAD Script password-store.ps1

So, genug geschrieben, schaut euch jetzt mein kleines Demo an.

Das Skript unterstützt auch die gängigen Parameter, speziell auch „verbose“

Nach dieser kleinen Einführung möchte ich auf einige Details, bzw. Funktionen innerhalb des Skriptes eingehen. Schaut euch die Kommentare an!

Funktion Create-AESKeyFile

function Create-AESKeyFile {
    [CmdletBinding(SupportsShouldProcess = $True)]
        param (
        [Parameter(Mandatory= $true)]
        [string]$keyFile)
    # Generate a random AES Encryption Key.
    # https://www.altaro.com/msp-dojo/encrypt-password-powershell/
    #what if parameter
    If ($PSCmdlet.ShouldProcess("Generating AES 256 bit key and write it to file `"$keyFile`"")) {
            $AESKey = New-Object Byte[] 32
            [Security.Cryptography.RNGCryptoServiceProvider]::Create().GetBytes($AESKey)
            #adding content to the specified key file
            Write-Verbose "Writing AES key to file $keyFile"
            Set-Content $Keyfile $AESKey
     }    
    else{
        #generate aes 256 bit key 
        $AESKey = New-Object Byte[] 32
        [Security.Cryptography.RNGCryptoServiceProvider]::Create().GetBytes($AESKey)
        #adding content to the specified key file
        Write-Verbose "Writing AES key to file $keyFile"
        Set-Content $Keyfile $AESKey
        #check if the file exists
        Write-Verbose "Checking if the encryption file $keyFile could be created"
        if (Test-Path $keyFile){
        Write-Output "writing key in $Keyfile !"
        #get the content of keyfile to display in verbose output
        $contentkey = Get-Content "$keyFile"
        Write-Verbose "this is your private key keep it safe"
        Write-Verbose "$contentkey"
        else{
            #clearing variable 
            Write-Verbose "Clearing aes key from variable!"
            $contentkey =$null
            throw "your file $keyFile could not be created, please check permissions or path!"
        }
    }
    #clearing variable
    Write-Verbose "Clearing aes key from variable!"
    $contentkey =$null
        }
    }

Funktion Create-CredFile

function Create-CredFile {
    [CmdletBinding(SupportsShouldProcess = $True)]
    param (
        [Parameter(Mandatory= $true)]
        [string]
        $credfile,
        [Parameter(Mandatory= $true)]
        [string]
        $aesfile
        )
        #getting password from user as secure string
        #whatif parameter
        If ($WhatIfPreference) {
            $passwordsecurestring = Read-Host "Enter a password to store encrypted" -AsSecureString  
            Write-Verbose "Encrypt securepassword string with AES 256 file: $aesfile!"
            Write-Verbose "Adding encrypted content to local file: $credfile"
            Write-Output "What if: $passwordsecurestring | ConvertFrom-SecureString -key (get-content "$aesfile") | set-content "$credfile""
        }
        else{
            #encrypt password and write in specified file
            $passwordsecurestring = Read-Host "Enter a password to store encrypted" -AsSecureString  
            Write-Verbose "Encrypt securepassword string with AES 256 file: $aesfile!"
            Write-Verbose "Adding encrypted content to local file: $credfile"
            $passwordsecurestring | ConvertFrom-SecureString -key (get-content "$aesfile") | set-content "$credfile"
            #check if the file exists
            if (Test-Path "$credfile"){
                #getting content from credfile only verbose
                $contentcred = Get-Content "$credfile"
                Write-Verbose "Content of ecnrypted file"
                Write-Verbose "$contentcred"
                #erase content from variable
                $contentcred = $null
            }
            else {
                #erase content from variable
                $contentcred =$null
                throw "your file $contentcred could does not exist, please check permissions or path!"
            }

        }
}

Die Funktionen können auch in anderen Skripten verwendet werden. Allerdings führen diese Funktionen keine große Fehlerbehandlung durch, da dies das Skript bereits bei der Abfrage der Parameter durchführt.

[CmdletBinding(SupportsShouldProcess = $True)]
param (
    #validating paths https://4sysops.com/archives/validating-file-and-folder-paths-in-powershell-parameters
    [Parameter(Mandatory = $true)]
    #test if the file exists, otherwise throw an error.Test if the user provides a full path to the file
    [ValidateScript({
        if(($_ | Test-path -PathType Leaf)){
            throw "File exists in path: $KeyfilePath, please provide another path and provide the filename example C:\temp\aes.key!"
        }
        if(($_ | Test-Path -PathType Container)){
            throw "The path argument has to be a file. Folder paths are not allowed."

        }
        return $true
    })]
    #check if it is a path
    [System.IO.FileInfo]$KeyfilePath,
    #test if the file exists, otherwise throw an error.Test if the user provides a full path to the file
    [Parameter(Mandatory = $true)]
    [ValidateScript({
        if(($_ | Test-path -PathType Leaf)){
            throw "File or Folder does exists in path: $CredFilePath, please provide another path and provide the filename example C:\temp\cred.txt!"
        }
        if(($_ | Test-Path -PathType Container)){
            throw "The path argument has to be a file. Folder paths are not allowed."

        }
        return $true
    })]
    #check if it is a path
    [System.IO.FileInfo]$CredFilePath
   
)

Hoffentlich gibt es hier kaum Wege der Funktion falsche Parameter mitzugeben. Am Ende führt das komplette Skript noch die beiden Funktionen aus.

Create-AESKeyFile -keyFile "$KeyfilePath"
Create-CredFile -credfile "$CredFilePath" -aesfile "$KeyfilePath"

Wenn euch das Skript /Artikel gefällt, klickt bitte auf „Helpful“. Freue mich auch immer über Anregungen und Kommentare.

Teil 2 Passwörter in PowerShell Skripten benutzen – Die Entschlüsselung

Print Friendly, PDF & Email
Was this article helpful?
YesNo
1 1 vote
Article Rating
Abonnieren
Benachrichtige mich bei
guest
1 Kommentar
Newest
Oldest Most Voted
Inline Feedbacks
View all comments
C. Mantek
C. Mantek
17 Tage zuvor

Hallo, danke für Anleitung, ich suche sowas in der Richtung um Office 2019 über eine Batch auf mehreren Rechnern zu installieren und muss dazu Anmeldeinformationen mit übergeben. Beim Ausführen des Script _passwort-store.ps1 um das Passwort zu verschlüsseln und den Key zu erzeugen erhalte ich aber folgende Meldung:
Cannot process argument transformation on parameter ‚KeyfilePath‘. Cannot convert value to type „System.IO.FileInfo“. Only core types are supported in this language mode.
können Sie hier weiter helfen?