Skip to content

Commit a6abf16

Browse files
authored
Add SecureStringHelper.FromPlainTextString (#14124)
1 parent 91e7298 commit a6abf16

File tree

3 files changed

+25
-8
lines changed

3 files changed

+25
-8
lines changed

src/Microsoft.PowerShell.Security/security/SecureStringCommands.cs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -359,8 +359,7 @@ protected override void ProcessRecord()
359359
}
360360
else
361361
{
362-
importedString = new SecureString();
363-
foreach (char currentChar in String) { importedString.AppendChar(currentChar); }
362+
importedString = SecureStringHelper.FromPlainTextString(String);
364363
}
365364
}
366365
catch (ArgumentException e)

src/System.Management.Automation/DscSupport/CimDSCParser.cs

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,8 @@
2222
using Microsoft.Management.Infrastructure.Serialization;
2323
using Microsoft.PowerShell.Commands;
2424

25+
using static Microsoft.PowerShell.SecureStringHelper;
26+
2527
namespace Microsoft.PowerShell.DesiredStateConfiguration.Internal
2628
{
2729
/// <summary>
@@ -259,12 +261,7 @@ private static object ConvertCimInstancePsCredential(string providerName, CimIns
259261
throw invalidOperationException;
260262
}
261263

262-
// Extract the password into a SecureString.
263-
var password = new SecureString();
264-
foreach (char t in plainPassWord)
265-
{
266-
password.AppendChar(t);
267-
}
264+
SecureString password = SecureStringHelper.FromPlainTextString(plainPassWord);
268265

269266
password.MakeReadOnly();
270267
return new PSCredential(userName, password);

src/System.Management.Automation/security/SecureStringHelper.cs

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
// Licensed under the MIT License.
33

44
using System;
5+
using System.Diagnostics;
56
using System.Globalization;
67
using System.IO;
78
using System.Management.Automation;
@@ -385,6 +386,26 @@ internal static SecureString Decrypt(string input, byte[] key, byte[] IV)
385386
return s;
386387
}
387388
}
389+
390+
#nullable enable
391+
/// <summary>Creates a new <see cref="SecureString"/> from a <see cref="string"/>.</summary>
392+
/// <param name="plainTextString">Plain text string. Must not be null.</param>
393+
/// <returns>A new SecureString.</returns>
394+
internal static unsafe SecureString FromPlainTextString(string plainTextString)
395+
{
396+
Debug.Assert(plainTextString is not null);
397+
398+
if (plainTextString.Length == 0)
399+
{
400+
return new SecureString();
401+
}
402+
403+
fixed (char* charsPtr = plainTextString)
404+
{
405+
return new SecureString(charsPtr, plainTextString.Length);
406+
}
407+
}
408+
#nullable restore
388409
}
389410

390411
/// <summary>

0 commit comments

Comments
 (0)