Last active
October 24, 2018 05:46
-
-
Save technoscavenger/b8a29314b404934ae23fc5d2ef1bd9e1 to your computer and use it in GitHub Desktop.
C# Convert SecureString to String
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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