Skip to content

Instantly share code, notes, and snippets.

@YounesCheikh
Created April 20, 2021 00:32
Show Gist options
  • Save YounesCheikh/03077ec5abf3aa2d0fadfa7cef35d898 to your computer and use it in GitHub Desktop.
Save YounesCheikh/03077ec5abf3aa2d0fadfa7cef35d898 to your computer and use it in GitHub Desktop.
String to SecureString and SecureString to String converter
static class SecureStringConverter
{
public static SecureString ConvertToSecureString(this string password)
{
if (password == null)
throw new ArgumentNullException("password");
unsafe
{
fixed (char* passwordChars = password)
{
var securePassword = new SecureString(passwordChars, password.Length);
securePassword.MakeReadOnly();
return securePassword;
}
}
}
public static string ConvertToString(this System.Security.SecureString str)
{
IntPtr bstr = Marshal.SecureStringToBSTR(str);
byte b = 1;
int i = 0;
string s = "";
while (((char)b) != '\0')
{
b = Marshal.ReadByte(bstr, i);
i += 2;
s += (char)b;
}
Marshal.FreeBSTR(bstr);
return s;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment