How to convert String
to SecureString
?
I'll throw this out there. Why?
You can't just change all your strings to secure strings and suddenly your application is "secure". Secure string is designed to keep the string encrypted for as long as possible, and only decrypted for a very short period of time, wiping the memory after an operation has been performed upon it.
I would hazard saying that you may have some design level issues to deal with before worrying about securing your application strings. Give us some more information on what your trying to do and we may be able to help better.
no fancy linq, not adding all the chars by hand, just plain and simple:
var str = "foo";
var sc = new SecureString();
foreach(char c in str) sc.appendChar(c);
You can follow this:
string password = "test";
SecureString sec_pass = new SecureString();
Array.ForEach(password.ToArray(), sec_pass.AppendChar);
sec_pass.MakeReadOnly();
Here is a cheap linq trick.
SecureString sec = new SecureString();
string pwd = "abc123"; /* Not Secure! */
pwd.ToCharArray().ToList().ForEach(sec.AppendChar);
/* and now : seal the deal */
sec.MakeReadOnly();
The following 2 extensions should do the trick:
For a char
array
public static SecureString ToSecureString(this char[] _self)
{
SecureString knox = new SecureString();
foreach (char c in _self)
{
knox.AppendChar(c);
}
return knox;
}
And for string
public static SecureString ToSecureString(this string _self)
{
SecureString knox = new SecureString();
char[] chars = _self.ToCharArray();
foreach (char c in chars)
{
knox.AppendChar(c);
}
return knox;
}
Thanks to John Dagg for the AppendChar
recommendation.
unsafe
{
fixed(char* psz = password)
return new SecureString(psz, password.Length);
}