Created
April 20, 2021 00:32
-
-
Save YounesCheikh/03077ec5abf3aa2d0fadfa7cef35d898 to your computer and use it in GitHub Desktop.
String to SecureString and SecureString to String converter
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
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