Skip to content

Instantly share code, notes, and snippets.

@gitfvb
Last active July 15, 2019 09:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gitfvb/9592dd38b9fae2c2a5d0f7e114d0b92a to your computer and use it in GitHub Desktop.
Save gitfvb/9592dd38b9fae2c2a5d0f7e114d0b92a to your computer and use it in GitHub Desktop.
Encrypt and decrypt string (like tokens) securely in PowerShell. This can be used to save tokens safely in a text file. The encryption key will be generated on the fly.
################################################
#
# SCRIPT ROOT
#
################################################
# Load scriptpath
if ($MyInvocation.MyCommand.CommandType -eq "ExternalScript") {
$scriptPath = Split-Path -Parent -Path $MyInvocation.MyCommand.Definition
} else {
$scriptPath = Split-Path -Parent -Path ([Environment]::GetCommandLineArgs()[0])
}
Set-Location -Path $scriptPath
################################################
#
# FUNCTIONS
#
################################################
Function Get-PlaintextToSecure {
param(
[Parameter(Mandatory=$true)][String]$String
)
# generate salt
Create-KeyFile -keyfilename "aes.key" -byteLength 32
$salt = Get-Content -Path "aes.key" -Encoding UTF8
# convert
$stringSecure = ConvertTo-secureString -String $String -asplaintext -force
$return = ConvertFrom-SecureString $stringSecure -Key $salt
# return
$return
}
Function Get-SecureToPlaintext {
param(
[Parameter(Mandatory=$true)][String]$String
)
# generate salt
$salt = Get-Content -Path "aes.key" -Encoding UTF8
#convert
$stringSecure = ConvertTo-SecureString -String $String -Key $salt
$return = (New-Object PSCredential "dummy",$stringSecure).GetNetworkCredential().Password
#return
$return
}
Function Create-KeyFile {
param(
[Parameter(Mandatory=$false)][string]$keyfilename = "aes.key"
,[Parameter(Mandatory=$false)][int]$byteLength = 32
)
$keyfile = ".\$( $keyfilename )"
# file does not exist -> create one
if ( (Test-Path -Path $keyfile) -eq $false ) {
$Key = New-Object Byte[] $byteLength # You can use 16, 24, or 32 for AES
[Security.Cryptography.RNGCryptoServiceProvider]::Create().GetBytes($Key)
$Key | Set-Content -Encoding UTF8 -Path $keyfile
}
}
$input = "abc"
$encrypted = Get-PlaintextToSecure -String "abc"
$decrypted = Get-SecureToPlaintext -String $encrypted
$input
$encrypted
$decrypted
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment