Monday 14 March 2016

PowerShell Script for Password encrypt, decrypt using secure key

Create/generate a key beforehand in separate script:

Advanced Encryption Standard(AES) encryption only supports 128-bit (16 bytes), 192-bit (24 bytes) or 256-bit key (32 bytes) lengths, so we’ll need to create or generate an appropriate key. Let’s create a byte array of ascending numbers. We will use a 192-bit key, so we’ll need a 24-byte array. 

Generate Secure Key :

generate_securekey.ps1
param
(
 [parameter(Mandatory=$true, Position=0)]
 [string] $File = $null,
 [parameter(Mandatory=$false, Position=1)]
 [string] $length = 24
)
$Key = New-Object Byte[] $length
[Security.Cryptography.RNGCryptoServiceProvider]::Create().GetBytes($Key)
$Key | out-file $File
Once you generate the secure key, you will be able to use the key file to encrypt or decrypt the password from any machine.

Encrypt Password using key:

encrypt_password.ps1
param
(
 [parameter(Mandatory=$true, Position=0)]
 [string] $PW = $null,
 [parameter(Mandatory=$true, Position=1)]
 [string] $SecureKeyFile = $null
)
$Key = Get-Content $SecureKeyFile
$Encrypted_PW = $PW | ConvertTo-SecureString -AsPlainText -Force
Write-Host "Encrypted password with $SecureKeyFile" -ForegroundColor "Cyan"
Write-Host "******************************************" -Foregroundcolor "Yellow"
$Encrypted_PW | ConvertFrom-SecureString -key $Key | Write-Output
Write-Host "******************************************" -Foregroundcolor "Yellow"
Decrypt Password using key:

decrypt_password.ps1
param
(
 [parameter(Mandatory=$true, Position=0)]
 [string] $EncryptedPW = $null,
 [parameter(Mandatory=$true, Position=1)]
 [string] $SecureKeyFile = $null
)
$Key = Get-Content $SecureKeyFile
$account = $env:userdomain + "\" + $env:username
$clearpw = (New-Object -TypeName System.Management.Automation.PSCredential -Argumentlist $account, (ConvertTo-SecureString -String $encryptedPW -key $key)).GetNetworkCredential().Password;
Write-Host "Password decrypted with $SecureKeyFile" -ForegroundColor "Cyan"
Write-Host "******************************************" -Foregroundcolor "Yellow"
$clearpw | write-Output
Write-Host "******************************************" -Foregroundcolor "Yellow"

No comments:

Post a Comment