I developed a PowerShell script which processes certain files and transfers them via SFTP. To do so, it uses the SecureString type to read and decrypt the SFTP user credentials from an encrypted text file whenever the credentials are needed to authenticate to the SFTP server. This is required because I am not allowed to store the credentials as plain text in a file (or in the script itself) because it would otherwise not pass the next security audit.
In addition to the script there is a separate configuration script which must be run once to specify the sftp user credentials, encrypt them and save them to the text file. This is the (simplified) code of that configuration script:
Write-Output "Please enter the username of the SFTP user."
$username = Read-Host
Write-Output "Please enter the password of the SFTP user"
$password = Read-Host -AsSecureString
$username | ConvertTo-SecureString -AsPlainText -Force | ConvertFrom-SecureString | Out-File "$scriptroot\Credentials.dat"
$password | ConvertFrom-SecureString | Out-File -Append "$scriptroot\Credentials.dat"
Basically the two scripts work just fine and do what they are supposed to. However, for whatever reason the decryption will stop working once I log out and then log back into windows again.
I do not understand why this stops working over and over again and I am not sure what to do about it. Does anybody know a way to figure out why the decryption stops working due to me logging out of the system? The script does not even run under my own user, it is executed as a scheduled task which runs under a completely different AD user.
I also read that Microsoft no longer recommends using SecureString for new projects, but then what is the alternative that can be used instead? How else am I supposed to securely store user credentials in a file without having some sort of plain text decryption key stored in the script or in another file somewhere?