无法将字符串转换为SecureString(拨号VPN)

时间:2019-04-15 19:41:08

标签: c# powershell vpn securestring

所以我得到了一个代码,该代码使用PowerShell和Radial在Windows 10中创建和连接VPN。

一切正常。

但是,当我想使用用户输入的凭据拨打VPN时,会出现错误。

这是我的代码:

Console.WriteLine("VPN Created.");
Console.WriteLine("Do you wanna connect? y/n");
string key = Console.ReadLine();

if (key == "y") {
    Console.WriteLine("Input username:");
    string username = Console.ReadLine();

    Console.WriteLine("Input password:");
    string password = Console.ReadLine();

    Console.WriteLine("Executing rasdial...");
    System.Diagnostics.Process.Start("rasdial.exe", "VPN_Arta {0} {1}", username, password);
}

我得到的错误是:

  

无法与启动rasdial.exe一起在线将字符串转换为System.Security.SecureString。

你们知道如何解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

所以我让它可以使用普通字符串,但是现在我需要在securestring中使用屏蔽密码来实现。

我的代码如下:

Console.WriteLine("Input username:");
            string username = Console.ReadLine();

            Console.WriteLine("Input password:");

            SecureString password = new SecureString();
            password = Classes.Functions.GetPassword();

            Classes.Functions.runProcRasdial("VPN_Arta", username, password);

            Console.Clear();
            Console.WriteLine("VPN Connected.");

调用rasdial的方法

public static Process runProcRasdial(string VPNName, string username, SecureString password)
    {

        ProcessStartInfo psi = new ProcessStartInfo("cmd")
        {
            RedirectStandardInput = true,
            RedirectStandardOutput = false,
            UseShellExecute = false
        };
        var proc = new Process()
        {
            StartInfo = psi,
            EnableRaisingEvents = true,
        };
        proc.Start();
        proc.StandardInput.WriteLine("rasdial {0} {1} {2}", VPNName, username, password);
        proc.StandardInput.WriteLine("exit");
        proc.WaitForExit();
        return proc;

    }

屏蔽密码的方法:

//mask password
    public static SecureString GetPassword()
    {
        var pwd = new SecureString();
        while (true)
        {
            ConsoleKeyInfo i = Console.ReadKey(true);
            if (i.Key == ConsoleKey.Enter)
            {
                break;
            }
            else if (i.Key == ConsoleKey.Backspace)
            {
                if (pwd.Length > 0)
                {
                    pwd.RemoveAt(pwd.Length - 1);
                    Console.Write("\b \b");
                }
            }
            else if (i.KeyChar != '\u0000' ) // KeyChar == '\u0000' if the key pressed does not correspond to a printable character, e.g. F1, Pause-Break, etc
            {
                pwd.AppendChar(i.KeyChar);
                Console.Write("*");
            }
            }
        return pwd;
    }

问题是我没有收到任何错误,一切看起来都很好。但是我认为屏蔽密码功能会出现问题,因为它不接受正确的密码,我也不知道。

你们有什么想法吗?

谢谢

约翰