Skip to content

Instantly share code, notes, and snippets.

@technoscavenger
Last active October 24, 2018 05:46
Show Gist options
  • Save technoscavenger/b8a29314b404934ae23fc5d2ef1bd9e1 to your computer and use it in GitHub Desktop.
Save technoscavenger/b8a29314b404934ae23fc5d2ef1bd9e1 to your computer and use it in GitHub Desktop.
C# Convert SecureString to String
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
var secure = new SecureString();
foreach (char c in "p@$$w0rd")
{
secure.AppendChar(c);
}
var password = new System.Net.NetworkCredential(string.Empty, secure).Password;
Console.WriteLine(password);
Func<SecureString, string> SecureToString = secureString =>
{
IntPtr valuePtr = IntPtr.Zero;
try
{
valuePtr = System.Runtime.InteropServices.Marshal.SecureStringToGlobalAllocUnicode(secureString);
return System.Runtime.InteropServices.Marshal.PtrToStringUni(valuePtr);
}
finally
{
System.Runtime.InteropServices.Marshal.ZeroFreeGlobalAllocUnicode(valuePtr);
}
};
var pass2 = SecureToString(secure);
Console.WriteLine(pass2);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment