PowerShell – Encrypt and Decrypt using SecureString

email me

#PART1
# create aes key - keep this secure at all times
$aesKey = (2,3,1,4,54,32,144,23,5,3,1,41,36,31,18,175,6,17,1,9,5,1,76,23)

# set string
$plaintext = "test12345$"

clear-host

Write-Host "Plaintext: $plaintext`n"

# convert to secure string object
$Secure = ConvertTo-SecureString -String $plaintext -AsPlainText -Force

# store secure object - use output in the decryption process. Could be saved to file.
# remember, the aeskey should remain physically secured
$encrypted = ConvertFrom-SecureString -SecureString $Secure -Key $aesKey
Write-Host "Encrypted:`n$encrypted`n"

#PART2
$aesKey = (2,3,1,4,54,32,144,23,5,3,1,41,36,31,18,175,6,17,1,9,5,1,76,23)
# create new object using $encrypted and $aeskey
$secureObject = ConvertTo-SecureString -String $encrypted -Key $aesKey

# perform decryption from secure object
$decrypted = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($secureObject)
$decrypted = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($decrypted)
$decrypted


Output

 

Notes

ConvertTo-SecureString

ConvertFrom-SecureString

Marshal.SecureStringToBSTR(SecureString) Method

Marshal.PtrToStringAuto Method

——-

$Password = Read-Host -AsSecureString
$UserAccount = Get-LocalUser -Name “User02”
$UserAccount | Set-LocalUser -Password $Password

——-

#PART1
$Password = read-host “Enter Password” -AsSecureString

In memory
01000000d08c9ddf0115d1118c7a00c04fc297eb01000000626ad2cb864d7e4fa0dd9b912ec43218000000000200000000001066000000010000200000001de2f898ea381168212c183a6db03c087c5
5aa40e9e4b10c84907da0060bd2f3000000000e80000000020000200000007c7a72e3be117aaba1c0d88103530cb7721b938c8e64204381b36a8018dedcb920000000f6c66b965a51c7b0aa46c4d7e4
01eaa981413ec1a4a9cafc847da6d27f32aec5400000005c2595bd588e0f596073ee6927be993c544aa3285b18d9339db120f37f00d1fcddc1f40fd952e615d04b4868eee2a60000e03d76886aff43f
0da793aeb8ea0d8

#PART2
$LocalAdminPassword = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($Password))

net user Administrator $LocalAdminPassword

——

#PART1
$SecurePassword = Read-Host “Enter Password” -asSecureString
$credentials = New-Object System.Management.Automation.PSCredential(“Administrator”, $SecurePassword)

#PART2
$LocalAdmin = [adsi](“WinNT://$env:COMPUTERNAME/Administrator, user”)
$LocalAdmin.SetPassword($credentials.GetNetworkCredential().Password)