I want the text entered in the textbox to be converted to securestring in c#.
The simplest approach is to iterate over the source string and append one character at a time to the secure string, like so:
var secure = new SecureString();
foreach (char c in textbox1.Text)
{
secure.AppendChar(c);
}
-
22Note that keeping the data in a plain string before being converted to SecureString beats the whole point of using SecureString. – Péter Török Feb 17 '14 at 10:52
-
7Google leads here. Internet answers referring to google are the most circular thing imaginable. If the question has already been asked on SO, that's another matter (and I'm sure it has). – Josh Sutterfield Feb 25 '16 at 0:03
-
9Am I the only one who finds it bewildering that the single most common
SecureString
use case requires a for loop? – Jake Aug 19 '16 at 19:22 -
@PéterTörök Indeed. However, things like the SqlConnection constructor taking an SqlCredential parameter has no other option than passing the password as a SecureString - so one is forced to use an insecure SecureString in this manner. – Joe Dyndale May 23 '17 at 6:44
-
@JoeDyndale , better to save
SqlCredential
parameter inMy.Settings
(Application Settings/Config file), while encrypting the setting file . so there is other option. Never use password coded in anyway, according to MS its recoverable with some tools after deploy Security Note. – wpcoder Aug 4 '17 at 23:16
Invent once and reuse lots. Create a simple extension method to extend the string base class and store it some static utilities class somewhere
using System.Security;
/// <summary>
/// Returns a Secure string from the source string
/// </summary>
/// <param name="Source"></param>
/// <returns></returns>
public static SecureString ToSecureString(this string source)
{
if (string.IsNullOrWhiteSpace(source))
return null;
else
{
SecureString result = new SecureString();
foreach (char c in source.ToCharArray())
result.AppendChar(c);
return result;
}
}
and then call as follows:
textbox1.Text.ToSecureString();
-
12Note that keeping the data in a plain string before being converted to SecureString beats the whole point of using SecureString. – Péter Török Feb 17 '14 at 10:52
-
1I would return an empty
SecureString
if the string is null or white space to represent a null or emptySecureString
.NullReferenceExceptions
can be cruel. – James M Sep 25 '16 at 17:30
You should make the SecureString readonly. So the code should look like this:
static class SecureStringExtensions
{
public static string ToUnsecureString(this SecureString secureString)
{
if (secureString == null) throw new ArgumentNullException("secureString");
var unmanagedString = IntPtr.Zero;
try
{
unmanagedString = Marshal.SecureStringToGlobalAllocUnicode(secureString);
return Marshal.PtrToStringUni(unmanagedString);
}
finally
{
Marshal.ZeroFreeGlobalAllocUnicode(unmanagedString);
}
}
public static SecureString ToSecureString(this string unsecureString)
{
if (unsecureString == null) throw new ArgumentNullException("unsecureString");
return unsecureString.Aggregate(new SecureString(), AppendChar, MakeReadOnly);
}
private static SecureString MakeReadOnly(SecureString ss)
{
ss.MakeReadOnly();
return ss;
}
private static SecureString AppendChar(SecureString ss, char c)
{
ss.AppendChar(c);
return ss;
}
}
-
2Small tweak to your code is to use 'nameof(securestring)' and 'nameof(unsecureString)' when throwing the ArgumentNullExceptions. In my implementation I used lambda's for AppendChar and MakeReadOnly, but that's just personal flavour sauce ;) – SSX-SL33PY Feb 3 '16 at 7:43
-
That was useful. Made a bunch of minor cleanups in my own version, but I didn't know about
Marshal.SecureStringToGlobalAllocUnicode
. -- Thanks! – BrainSlugs83 Jun 23 '16 at 19:01
It may be a little late but you can convert SecureString to String this way either
using System.Security;
.
.
.
/// <summary>
/// Converts String to SecureString
/// </summary>
/// <param name="input">Input in String</param>
/// <returns>Input in SecureString</returns>
public SecureString String2SecureString(String input) {
SecureString _output = new SecureString();
input.ToCharArray().ToList().ForEach((q) => _output.AppendChar(q));
return _output;
}
although it all the same as Balazs Tihanyi's answer:
Google is your friend...
var secure = new SecureString(); foreach(char c in textbox1.Text) { secure.AppendChar(c); }
-
3You don't need
.ToCharArray()
so justinput.ToList().ForEach(q => _output.AppendChar(q));
– knguyen Oct 22 '15 at 17:49 -
-
4
I'm supprised nobody metioned about SecureString constructor taking pointer to char array.
public static SecureString ToSecureString(this string source)
{
char[] charArray = source.ToCharArray();
unsafe
{
fixed (char* chars = charArray)
{
return new SecureString(chars, charArray.Length);
}
}
}
Note that this code only works with /unsafe
compiler option. To set this option go to project properties, Build tab and check Allow unsafe code checkbox.
-
Can't find this option! where is it in Visual Studio 2017? what is the use? – wpcoder Aug 4 '17 at 22:51
-
@wpcoder What kind of project do you have? Windows Universal, Windows Classic Desktop or something else? – Szybki Aug 7 '17 at 11:43
-
Windows forms , I am referring to how to add
/unsafe
in vs 2017, and what is the benefits? – wpcoder Aug 7 '17 at 13:02 -
1@wpcoder In VS2017 there's pretty much the same way of adding
/unsafe
parameter as in earlier VS versions - right click on your WinForms project in theProject Explorer
and selectProperties
or double click on theProperties
item under your WinForms project in theProject Explorer
. Then selectBuild
tab and check theAllow unsafe code
checkbox. This will allow you to use theunsafe { }
context which is required to use pointers in managed code. – Szybki Aug 7 '17 at 14:25 -
Thank you @Szybki , but can't find it in VS2017 CE, anyway I got what is the benefits. – wpcoder Aug 7 '17 at 15:19
Nearly the same, but shorter:
SecureString secureString = new SecureString();
textbox1.Text.ToCharArray().ForEach(c => secureString.AppendChar(c));
use this for the event handler on your text box:
private void textbox1_TextChanged(object sender, EventArgs e)
{
SecureString newSecureTextBox = new SecureString();
foreach (char c in textbox1.Text.ToCharArray())
{
newSecureTextBox.AppendChar(c);
}
}
call your variable normally as newSecureTextBox
-
1A nice thought, but I think you meant
LostFocus
, notTextChanged
. Everytime a key is pressed the TextChanged event fires, so it's rebuilding each time as they would be trying to type a keystroke. And why.ToCharArray()
? You can get the chars from the.Text
just fine. – vapcguy Jan 24 '17 at 21:45
var output = new SecureString(); input.ToList().ForEach(output.AppendChar);
. – BrainSlugs83 Jun 23 '16 at 18:44