I want the text entered in the textbox to be converted to securestring in c#.
Description. The ConvertTo-SecureString cmdlet converts encrypted standard strings into secure strings. It can also convert plain text to secure strings. It is used with ConvertFrom-SecureString and Read-Host .
A SecureString object should never be constructed from a String, because the sensitive data is already subject to the memory persistence consequences of the immutable String class. The best way to construct a SecureString object is from a character-at-a-time unmanaged source, such as the Console. ReadKey method.
The encrypted standard string can be converted back to its secure string format by using the ConvertTo-SecureString cmdlet.
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);
}
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();
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With