Add SecureStringHelper.FromPlainTextString (#14124)

This commit is contained in:
xtqqczze
2021-04-12 14:05:20 -07:00
committed by GitHub
parent 91e7298fd8
commit a6abf16941
3 changed files with 25 additions and 8 deletions
@@ -359,8 +359,7 @@ namespace Microsoft.PowerShell.Commands
}
else
{
importedString = new SecureString();
foreach (char currentChar in String) { importedString.AppendChar(currentChar); }
importedString = SecureStringHelper.FromPlainTextString(String);
}
}
catch (ArgumentException e)
@@ -22,6 +22,8 @@ using Microsoft.Management.Infrastructure.Generic;
using Microsoft.Management.Infrastructure.Serialization;
using Microsoft.PowerShell.Commands;
using static Microsoft.PowerShell.SecureStringHelper;
namespace Microsoft.PowerShell.DesiredStateConfiguration.Internal
{
/// <summary>
@@ -259,12 +261,7 @@ namespace Microsoft.PowerShell.DesiredStateConfiguration.Internal
throw invalidOperationException;
}
// Extract the password into a SecureString.
var password = new SecureString();
foreach (char t in plainPassWord)
{
password.AppendChar(t);
}
SecureString password = SecureStringHelper.FromPlainTextString(plainPassWord);
password.MakeReadOnly();
return new PSCredential(userName, password);
@@ -2,6 +2,7 @@
// Licensed under the MIT License.
using System;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Management.Automation;
@@ -385,6 +386,26 @@ namespace Microsoft.PowerShell
return s;
}
}
#nullable enable
/// <summary>Creates a new <see cref="SecureString"/> from a <see cref="string"/>.</summary>
/// <param name="plainTextString">Plain text string. Must not be null.</param>
/// <returns>A new SecureString.</returns>
internal static unsafe SecureString FromPlainTextString(string plainTextString)
{
Debug.Assert(plainTextString is not null);
if (plainTextString.Length == 0)
{
return new SecureString();
}
fixed (char* charsPtr = plainTextString)
{
return new SecureString(charsPtr, plainTextString.Length);
}
}
#nullable restore
}
/// <summary>