Powershell: Encrypt and decrypt strings with the host key

Hi,

each Windows machine has it’s own host key. This can be used to encrypt data which are only decrypted by this computer.


Load requiered assembly

[System.reflection.assembly]::LoadWithPartialName("System.Security") | out-null

Encrypt

# Encrypt
$MySecret="fdgsdfghdfghasdfagfdfgsdgdfgsdfgsdfg"
write-host "Key" $MySecret
$MySecretBytes=[System.Text.Encoding]::unicode.GetBytes($MySecret)
$sSecretBytesEncrypted=[System.Security.Cryptography.ProtectedData]::protect($MySecretBytes  ,$null,[System.Security.Cryptography.DataProtectionScope]::LocalMachine)
$sSecretBase64=[Convert]::ToBase64String($sSecretBytesEncrypted)

& setx /m ITAM $sSecretBase64
Decrypt

# Decrypt
$sSecretBytesEncrypted=[System.Convert]::FromBase64String($sSecretBase64)
$MySecretBytes=[System.Security.Cryptography.ProtectedData]::Unprotect($sSecretBytesEncrypted,$null,[System.Security.Cryptography.DataProtectionScope]::LocalMachine)
$MySecret=[System.Text.Encoding]::unicode.GetString($MySecretBytes)
write-host "Key" $MySecret

This also works only for an user. Simply set the scope to of the protect and unprotect functiona to

[System.Security.Cryptography.DataProtectionScope]::CurrentUser

Michael

Advertisment to support michlstechblog.info

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.