PoshCode Archive  Artifact [a98e385102]

Artifact a98e3851024c19693960feed9a412d0004556abbf7a9d7eba03472532efa0052:

  • File secure-passwords.ps1 — part of check-in [ff4a91425a] at 2018-06-10 14:01:46 on branch trunk — Encrypting and Decrypting passwords using securestring. Simple example. (user: BattleChicken size: 2692)

# encoding: ascii
# api: powershell
# title: secure passwords
# description: Encrypting and Decrypting passwords using securestring.  Simple example.
# version: 0.1
# type: function
# author: BattleChicken
# license: CC0
# function: Get-PasswordFromEncryptedFile
# x-poshcode-id: 5807
# x-archived: 2015-04-03T14:47:08
# x-published: 2015-04-01T18:20:00
#
#
Function Get-PasswordFromEncryptedFile {
<#
.Synopsis
   Converts a password stored as a secure string to a file to plain text.
.DESCRIPTION
   Converts a password stored as a secure string to a file to plain text.
.EXAMPLE
   Get-PasswordFromEncryptedFile -PasswordFile "c:\admin\MyEncryptedPass.txt"
   Assuming the user who encryptedt he password is the same user executing the command, will decrypt the string in c:\admin\MyEncryptedPass.txt to plain-text.
.OUTPUTS
   Outputs a string object
.NOTES
   This function can be tricky.  it decrypts a securestring, so it will only be reversible by the same user that created the original encrypted file.  So, if my user is MyDomain\MyUsername, only MyDomain\MyUsername on the same machine can reverse the encryption.  Keep in mind the decrypt will only work if you created the file on that same machine.
.FUNCTIONALITY
   Decrypts a secure string saved to a file.
#>
    param(
        [parameter(Mandatory=$true)]
        [string]$PasswordFile
    )

    if (-not (Test-Path $PasswordFile)){
        throw "Nonexistent Password file"
    }
    else {
        try{
            $encryptedPass = get-content $PasswordFile | ConvertTo-SecureString
            $encryptedStr = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($encryptedPass)
            [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($encryptedStr)
            [Runtime.InteropServices.Marshal]::ZeroFreeBSTR($encryptedStr) # Cleanup to avoid memory leak
        }
        catch {
            throw "Error decrypting Secure string.  Only files encrypted by $env:USERNAME on $env:COMPUTERNAME can be decrypted in this session."
        }

    }
}

Function New-PasswordFile {
<#
.Synopsis
   Saves a string (a password most likely) to the specified file.
.DESCRIPTION
   Saves a string (a password most likely) to the specified file.
.EXAMPLE
   New-PasswordFile -PasswordFile c:\admin\MyEncryptedPassword.txt
   Prompts the user for a string, which gets saved encrypted to c:\admin\MyEncryptedPassword.txt
#>
    param(
        [parameter(Mandatory=$true)]
        [string]$PasswordFile
    )

    read-host -AsSecureString "Enter a password" | ConvertFrom-SecureString -ErrorAction stop| out-file $PasswordFile -ErrorAction Stop