Convert a SecureString to a String (Plain Text) in PowerShell

by dstock 29. March 2009 18:30

Repost from my old Blog:

In PowerShell I was looking for a way to let a user enter a password while hiding the characters they typed.  My reason for this is that I wanted to pass it as command line parameter to an application.  I found that the built in Read-Host -assecurestring would cover the users typing with astricks but the object returned was a SecureString.

The securestring object does not have a property or method to allow you to retrieve the unencrypted string.  The reason for this is for security.  You need to explicitly write something if you need to get the string.  In many cases you will be able to provide the SecureString to other objects that will use it for such things as credentials

To get the convert a securestring to a string value you need to first use the Marshal Object to convert the SecureString to a intPtr (pointer).  Then use the Marshal's method of PtrToStringAuto to convert the intPtr into a string. 

The example code is:
$secret=[Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR((read-host -assecurestring)))

If you found this useful, please click one of the Google links.

Currently rated 5.0 by 1 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

PowerShell

Comments

Comments are closed

Powered by BlogEngine.NET 1.4.5.0
Theme by Extensive SEO

About the blog

Focusing on PeopleSoft, SQL, PowerShell, C# and anything else that tweaks my interest