Reputation: 61
I want to encrypt a text which I want to use in different PowerShell script without compromising its security as other user will be using scripts that will contain that text. Basically I want to conceal that text from everybody and use it without any hassle to all PowerShell scripts that are using that particular text. Text can be stored in a file so that it will be used in different scripts. I have tried basic things like :
$text = Read-Host "Enter the text" -AsSecureString
$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($text)
$Plaintext = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)
Write-Host "Text is: " $PlainText
But the thing is it can easily be found if you are in same computer. I need some foolproof method if any.This is my first question so please ignore my mistakes, if any.
Upvotes: 2
Views: 2302
Reputation: 9163
In your case, you need a specific key to make the string encrypted.
For Setting the Key:
function Set-Key {
param([string]$string)
$length = $string.length
$pad = 32-$length
if (($length -lt 16) -or ($length -gt 32)) {Throw "String must be between 16 and 32 characters"}
$encoding = New-Object System.Text.ASCIIEncoding
$bytes = $encoding.GetBytes($string + "0" * $pad)
return $bytes
}
For Setting the Encrypted Data:
function Set-EncryptedData {
param($key,[string]$plainText)
$securestring = new-object System.Security.SecureString
$chars = $plainText.toCharArray()
foreach ($char in $chars) {$secureString.AppendChar($char)}
$encryptedData = ConvertFrom-SecureString -SecureString $secureString -Key $key
return $encryptedData
}
For Decrypting the data:
function Get-EncryptedData {
param($key,$data)
$data | ConvertTo-SecureString -key $key |
ForEach-Object {[Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($_))}
}
How to use:
$plainText = "Some Super Secret Password"
$key = Set-Key "AGoodKeyThatNoOneElseWillKnow"
$encryptedTextThatIcouldSaveToFile = Set-EncryptedData -key $key -plainText $plaintext
$encryptedTextThatIcouldSaveToFile ## - sample output 507964ed3a197b26969adead0212743c378a478c64007c477efbb21be5748670a7543cb21135ec324e37f80f66d17c76c4a75f6783de126658bce09ef19d50da
$DecryptedText = Get-EncryptedData -data $encryptedTextThatIcouldSaveToFile -key $key
$DecryptedText
Reference Link: Encrypting & Decrypting Strings with PS
Hope it helps.
Upvotes: 2