Im trying to encrypt and decrypt passwords, i've made 2 functions:
function VA-EncryptPassword {
param(
[Parameter(Mandatory=$true)]
[string]$PlainPassword
)
# Add assembly for security
Add-Type -AssemblyName "System.Security"
# Convert password string to a byte array
$PlainPasswordBytes = [System.Text.Encoding]::Unicode.GetBytes($PlainPassword)
# Encrypt the password (machine-specific)
$EncryptedPassword = [System.Security.Cryptography.ProtectedData]::Protect($PlainPasswordBytes, $null, [System.Security.Cryptography.DataProtectionScope]::LocalMachine)
# Optionally, convert the byte array to Base64 for easier storage or transmission
$Encrypted64Password = [Convert]::ToBase64String($EncryptedPassword)
# Return the Base64 encrypted password
$Encrypted64Password
}
function VA-DecryptPassword {
param(
[Parameter(Mandatory=$true)]
[string]$Encrypted64Password
)
# Add assembly for security
Add-Type -AssemblyName System.Security
Add-Type -AssemblyName System.Text.Encoding
# Convert the Base64 encrypted password back to a byte array
$EncryptedPasswordBytes = [Convert]::FromBase64String($Encrypted64Password)
# Decrypt the password using DPAPI
$DecryptedPasswordBytes = [System.Security.Cryptography.ProtectedData]::Unprotect($EncryptedPasswordBytes, $null, [System.Security.Cryptography.DataProtectionScope]::LocalMachine)
# Convert byte array back to a string
$DecryptedPassword = [System.Text.Encoding]::Unicode.GetString($DecryptedPasswordBytes)
# Return the decrypted password
$DecryptedPassword
}
I get: exception calling "unprotect" with "3" arguments: "The operation completed successfully" Which means, it runs it but the result is null (?)
It functions correctly on several servers, except 2. The tricky part is, if i run the script in the Powershell ISE, i can do both encrypt and decrypt. However, i can't decrypt do it with neither Console nor' Scheduled Task.
I can encrypt with the console, and decrypt with the ISE. But i can't for the life of me decrypt with console.
I've checked everything i could think of, Env:, $Profile, Features on the serves that work vs. the ones that doesn't, try as admin, regular user, checked .Net Framework and Core versions, and they both run powershell 5.xx (identical)
I hope someone has a bright idea, or has run into the issue themselves.