1

I have read this blog:

https://gallery.technet.microsoft.com/scriptcenter/Encrypt-Password-and-use-dd07f253

I have test this lines of code:

$encrypted = "01000000d08c9ddf0115d1118c7a00c04fc297eb010000000ffb51b2e604034a982598093219de570000000002000000000003660000c0000000100000004387d7a6f294bdcf25725159f7edaa390000000004800000a000000010000000efac6eb2cb924bf1cf893a9ddfdeeff71800000079b98b725901857051e84b78ba6e20da94752516a02833c114000000dbf49438a6ea07c06c3846fc23e725a081792782" 
$password = ConvertTo-SecureString -string $encrypted 

I get this error:

ConvertTo-SecureString : Clé non valide pour l'utilisation dans l'état spécifié.

Any idea ? Why do i get this error ?

Thanks

Bob5421
  • 7,757
  • 14
  • 81
  • 175
  • 4
    Does this answer your question? [Saving credentials for reuse by powershell and error ConvertTo-SecureString : Key not valid for use in specified state](https://stackoverflow.com/questions/7109958/saving-credentials-for-reuse-by-powershell-and-error-convertto-securestring-ke) – Andrew Ryan Davis Aug 28 '20 at 19:57

3 Answers3

5

You won't be able to decrypt the example string on your machine that easily because Windows uses the local user and machine account to "encrypt" the password. This process uses the Windows Data Protection API - DPAPI. If you need to use ConvertFrom-SecureString or ConvertTo-SecureString across multiple machines/accounts, which I wouldn't advise, then you would have to specify a key (see the parameters of the functions). Where do you then secure the key? Well...

The article is just an example of how to use it. You can copy and paste the following two code blocks to sample it without doing any file checking or further copying and pasting.

$SecureString = Read-Host -Prompt "Enter your Password" -AsSecureString
$EncryptedString = ConvertFrom-SecureString $SecureString 
$EncryptedString | Out-File .\Clowns.txt  # Because who would look inside, right?

To get the password back out in to a usable credential variable like the article, you'd do this.

$EncryptedString = Get-Content .\Clowns.txt
$SecureString = ConvertTo-SecureString $EncryptedString
$Credential = New-Object System.Management.Automation.PSCredential -ArgumentList "username",$SecureString

Another option, here is to use Export-Clixml to save credential files, which carries out the same DPAPI operation on a set of credentials.

$SecureString = Read-Host -Prompt "Enter your Password" -AsSecureString
$Credential = New-Object System.Management.Automation.PSCredential -ArgumentList "username",$SecureString
$Credential | Export-Clixml -Path .\Dolphins.xml    # Horrible, horrible beings.

You can then use Import-Clixml to recover the credentials with the same user account that "encrypted" them on the same machine.

$Credential = Import-Clixml -Path .\Dolphins.xml

If this is for just keeping credentials for yourself locally, it's not a terrible option. If it's for anything else, I would prefer some password vault that you can securely use via code.

Ash
  • 3,030
  • 3
  • 15
  • 33
2

You can do it like this:

Read the password from the console with hidden characters

$password = Read-Host "Enter your password" -AsSecureString

Then reveal it to pass it somewhere

$password = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($password))

Right after you pass it you can remove the variable

Remove-Variable password
Ash
  • 3,030
  • 3
  • 15
  • 33
Baequiraheal
  • 119
  • 1
  • 13
2

There are really not many use cases, where you'd need to decrypt it to plain text vs just using the object. Your use case will determine that.

However, there are a number of ways to secure credentials for use in PowerShell automation, decrypted not.

Starting with the cmdlet designed for it.

# Get specifics for a module, cmdlet, or function
(Get-Command -Name Get-Credential).Parameters
(Get-Command -Name Get-Credential).Parameters.Keys
Get-help -Name Get-Credential -Examples
Get-help -Name Get-Credential -Full
Get-help -Name Get-Credential -Online

$Creds = Get-Credential -Credential $env:USERDOMAIN\$env:USERNAME
$Creds.UserName
# Results
<#
lab01\Postanote
#>

$Creds.Password
# Results
<#
System.Security.SecureString
#>

$Creds.GetNetworkCredential().password
# Results
<#
TestMe
#>


# Using the Windows Credential Manager - there are many prebuilt modules for this
Find-Module -Name '*credential*' | 
Format-Table -AutoSize
# Results
<#
Version        Name                          Repository Description                                                                                                
-------        ----                          ---------- -----------                                                                                                
2.0            CredentialManager             PSGallery  Provides access to credentials in the Windows Credential Manager                                           
1.0.4          WindowsCredential             PSGallery  Management module for Windows Credential Store.                                                            
...
1.0.11         pscredentialmanager           PSGallery  This module allows management and automation of Windows cached credentials.                                
...
1.1.7          CredentialStore               PSGallery  CredentialStore saves powershell credentials securely to file                                              
2.1.0          PSJsonCredential              PSGallery  A set of commands for exporting and importing PSCredentials to a json file.                                
..
2.0.4.0        StoredPSCredential            PSGallery  Stores serialized PSCredential objects in HKCU and retrieves them. Encryption can only be reversed by th...
1.0.0          CredentialLocker              PSGallery  CredentialLocker is a module that provides commandlets to manage credentials in the password vault....     
1.0.1          MrACredential                 PSGallery  A module to manage creating, saving, and importing credentials using encryption keys.                      
1.0.3          CredentialManagement          PSGallery  Manage Credentials stored in the Windows Credential Manager                                                
...
1.1            CredentialsManager            PSGallery  The module Credentials Manager provides you with convenient and safe way to store your credentials to fi...
...
2.1            SecuredCredential             PSGallery  SecuredCredential Routines for modules supported. This module is published in my new book 'Cloud Integra...
1.0.477        PSCredentialStore             PSGallery  A simple credential manager to store and reuse multiple credential objects.
#>

Many other articles on the topic since is a well-documented use case. For Example: Just searching for 'PowerShell secure password' will give you tons to work with. For example...

Securely Store Credentials on Disk

Quickly and securely storing your credentials – PowerShell

Even using an AESKey

Using saved credentials securely in PowerShell scripts

# Generate a random AES Encryption Key.
$AESKey = New-Object Byte[] 32
[Security.Cryptography.RNGCryptoServiceProvider]::Create().GetBytes($AESKey)

# Store the AESKey into a file. This file should be protected!  (e.g. ACL on the file to allow only select people to read)
Set-Content $AESKeyFilePath $AESKey   # Any existing AES Key file will be overwritten       

$password = $passwordSecureString | ConvertFrom-SecureString -Key $AESKey
Add-Content $credentialFilePath $password

# To re-read the password, the following is done:
$username = "reasonable.admin@acme.com.au"
$AESKey = Get-Content $AESKeyFilePath
$pwdTxt = Get-Content $SecurePwdFilePath
$securePwd = $pwdTxt | ConvertTo-SecureString -Key $AESKey
$credObject = New-Object System.Management.Automation.PSCredential -ArgumentList $username, $securePwd
postanote
  • 15,138
  • 2
  • 14
  • 25