How to convert string into Secure string in C#
By FoxLearn 7/6/2024 3:56:17 AM 321
Importantly, SecureString
objects are automatically erased from memory when no longer needed, minimizing exposure to potential security threats.
Here's an extension method in C# that constructs a SecureString
from a plain string
public static class SecureStringExtensions { // c# extension method to convert string to SecureString public static SecureString ToSecureString(this string plainString) { if (plainString == null) throw new ArgumentNullException(nameof(plainString)); SecureString secureString = new SecureString(); foreach (char c in plainString) secureString.AppendChar(c); // make the SecureString immutable secureString.MakeReadOnly(); return secureString; } }
You can easily call SecureString directly on the string.
string password = "mySecurePassword123"; SecureString securePassword = password.ToSecureString(); // Ensure the SecureString is cleared from memory when no longer needed securePassword.Dispose();
The SecureStringExtensions
is a static class contains an extension method ToSecureString that extends the functionality of the string type.
Use the ToSecureString extension method takes a plain string as input and converts it into a SecureString. It iterates over each character in the input string and appends it to the SecureString.
If you want to convert a secure string into a normal plain text string you can use NetworkCredential
in C#
string plainString = new System.Net.NetworkCredential(string.Empty, securePassword).Password;
- How to fix 'Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on'
- How to use BlockingCollection in C#
- Calculating the Distance Between Two Coordinates in C#
- Could Not Find an Implementation of the Query Pattern
- Fixing Invalid Parameter Type in Attribute Constructor
- Objects added to a BindingSource’s list must all be of the same type
- How to use dictionary with tuples in C#
- How to convert a dictionary to a list in C#