Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 21 additions & 16 deletions src/Microsoft.PowerShell.Security/security/SecureStringCommands.cs
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,12 @@ public SecureString SecureString
}
}

/// <summary>
/// Gets or sets a switch to get the secure string as plain text.
/// </summary>
[Parameter(ParameterSetName = "AsPlainText")]
public SwitchParameter AsPlainText { get; set; }

/// <summary>
/// Processes records from the input pipeline.
/// For each input object, the command encrypts
Expand All @@ -165,6 +171,19 @@ protected override void ProcessRecord()
{
encryptionResult = SecureStringHelper.Encrypt(SecureString, Key);
}
else if (AsPlainText)
{
IntPtr valuePtr = IntPtr.Zero;
try
{
valuePtr = Marshal.SecureStringToGlobalAllocUnicode(SecureString);
exportedString = Marshal.PtrToStringUni(valuePtr);
}
finally
{
Marshal.ZeroFreeGlobalAllocUnicode(valuePtr);
}
}
else
{
exportedString = SecureStringHelper.Protect(SecureString);
Expand Down Expand Up @@ -342,22 +361,8 @@ protected override void ProcessRecord()
}
else
{
if (!Force)
{
string error =
SecureStringCommands.ForceRequired;
Exception e = new ArgumentException(error);
WriteError(new ErrorRecord(e, "ImportSecureString_ForceRequired", ErrorCategory.InvalidArgument, null));
}
else
{
// The entire purpose of the SecureString is to prevent a secret from being
// permanently stored in memory as a .Net string. If they use the
// -AsPlainText and -Force flags, they consciously have made the decision to be OK
// with that.
importedString = new SecureString();
foreach (char currentChar in String) { importedString.AppendChar(currentChar); }
}
importedString = new SecureString();
foreach (char currentChar in String) { importedString.AppendChar(currentChar); }
}
}
catch (ArgumentException e)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,11 @@ Describe "SecureString conversion tests" -Tags "CI" {
$ss = ConvertTo-SecureString -AsPlainText -Force abcd
$ss | Should -BeOfType SecureString
}

It "can convert back from a secure string" {
$secret = "abcd"
$ss1 = ConvertTo-SecureString -AsPlainText -Force $secret
$ss2 = convertfrom-securestring $ss1 | convertto-securestring
[pscredential]::New("user",$ss2).GetNetworkCredential().Password | Should -Be $secret
$ss2 = ConvertFrom-SecureString $ss1 | ConvertTo-SecureString
$ss2 | ConvertFrom-SecureString -AsPlainText | Should -Be $secret
}
}