简体   繁体   中英

Decrypt SecureString from Powershell with C#

I have following Powershell-Code to encrypt my password

$my_secure_password = convertto-securestring "myPW" -asplaintext -force $my_encrypted_string = convertfrom-securestring $my_secure_password -key(1..16)

The Output is something like this 76492d1116743f0423413b16050a5345MgB8AHMASgB1AFMARwBxAFMAYgA1AFIAYwAyAE4AOABqAHMAOQBaADgAbwBGAEEAPQA9AHwANwBk................

How can I decrypt this output in C# in order to use it as a SecureString in C#?

I've tested something like this but this didn't work for me

var runSpace_new = RunspaceFactory.CreateRunspace();
runSpace_new.Open();

PowerShell PSinstance = PowerShell.Create();
PSinstance.AddScript("$decrypt = convertto-securestring -key (1..16) -string 76492d1116743f0423413b.......");
var psOutput_new = PSinstance.Invoke();
var a = runSpace_new.SessionStateProxy.PSVariable.GetValue("decrypt");

But a is null....

UPDATE I have found a solution for this:

SecureString new_sec_pass = new SecureString();
PowerShell instance = PowerShell.Create();

instance.AddScript("convertto-securestring -key (1..16) -string 76492d1...");

foreach (PSObject psOutput in instance.Invoke())
{
    new_sec_pass = psOutput.BaseObject as SecureString;
}

PSCredential new_credentials = new PSCredential(Username, new_sec_pass);

You may try this (maybe it help for you - for me - it is work):

using System.Collections.ObjectModel;
using System.Management.Automation;

     static void Main(string[] args)
        {

            var variable = PowerShell.Create().AddScript("$xtr = convertto-securestring -key (1..16) -string" + 
            " '76492d1116743f0423413b16050a5345MgB8AEQAbQBIAEIASQB6ADcAeQA0AH" + 
            "UAaAB6AFEAawBJAEYAVAA0AHcAUwBoAGcAPQA9AHwAMQAzAGUANwBmADIAOAAxADEANwAwAGUAZQBjADMANwBlAG" +
            "QAYQAxADcAZABlADEAMQBhAGYAZgBiADkAOQBiADIAMAAwAGMAMgA1AGEAZgAxADcAMABhADAAYwBjAGIAMQBhADAAZAAwADMAMwAzADMAOQAwADcAYQAzAGMANwA='" + 
            ";$PwdPointer = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($xtr);"+
            "$PlainTextPassword = [Runtime.InteropServices.Marshal]::PtrToStringAuto($PwdPointer);$PlainTextPassword").AddCommand("out-string");
        Collection<PSObject> results = variable.Invoke();

            foreach (var str in results)
            {

                Console.WriteLine(str);
                Console.ReadKey();

            }
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM