1

嗨,我有一个包含两个值的 xml 文件。

第一个值是 Powershell 的用户名第二个值是密码作为 powershell 的安全字符串

现在我想读取这些值并将其设置为变量字符串 ps_user 和 SecureString ps_password

我现在的问题是如何使用 SecureString 值。

这是我的xml:

<?xml version="1.0" encoding="iso-8859-1"?>

<Credential>
  <User value="tarasov" />
  <SecurePassword value="0d08c9ddf0004800000a0000340b62f9d614" />
</Credential>

这是我的 C# 代码:

private string GetPowershellCredentials(string path, string attribute) 
        {
            XDocument document;
            string value = string.Empty;

            try
            {
                document = XDocument.Load(path);

                value = document.Element("Credential").Element(attribute).Attribute("value").Value;

                return value;
            }
            catch (Exception)
            {
                return null;
            }
            finally
            {
                document = null;
            }
        }

例子:

> string path = Server.MapPath("~/App_Data/Powershell_credentials.xml");

> string ps_user = GetPowershellCredentials(path, "User"); // It works

> SecureString ps_password  = GetPowershellCredentials(path,"SecurePassword"); // this not :((

我怎么能做到这一点?

4

1 回答 1

1

是因为您的 GetPowershellCredentials 返回一个字符串。这无法自动转换。如果你需要一个安全字符串,你可以使用这样的东西:

public static SecureString ToSecureString(string source)
{
      if (string.IsNullOrWhiteSpace(source))
            return null;
      else
      {
            SecureString result = new SecureString();
            foreach (char c in source.ToCharArray())
                result.AppendChar(c);
            return result;
      }
}

和这个:

SecureString ps_password  = ToSecureString(GetPowershellCredentials(path, "SecurePassword"));
于 2014-05-22T11:39:48.660 回答