How to convert string into Secure string in C#
By FoxLearn 3/19/2025 8:40:37 AM 789
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
// c# convert string to securestring 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)); // convert string to securestring c# SecureString secureString = new SecureString(); // string securestring to c# foreach (char c in plainString) secureString.AppendChar(c); // make the SecureString immutable secureString.MakeReadOnly(); return secureString; // c# securestring } }
You can easily call SecureString
directly on the string.
// c# string to securestring string password = "mySecurePassword123"; SecureString securePassword = password.ToSecureString(); // c# string to secure string // 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;
- Primitive types in C#
- How to set permissions for a directory in C#
- How to Convert Int to Byte Array in C#
- How to Convert string list to int list in C#
- How to convert timestamp to date in C#
- How to Get all files in a folder in C#
- How to use Channel as an async queue in C#
- Case sensitivity in JSON deserialization