Convert String to SecureString in C#
In C#, strings are commonly used to store sensitive information such as passwords, API keys, and other confidential data. However, strings are immutable, meaning they can't be changed once created. This presents a security risk because strings are stored in memory as plain text, making them susceptible to being accessed by malicious actors.
To address this issue, .NET provides the SecureString
class, which offers a more secure way to store sensitive data in memory. SecureString
encrypts the data and stores it in an encrypted format, making it less vulnerable to attacks.
using System;
using System.Security;
class Program
{
static void Main(string[] args)
{
string password = "MySecretPassword@010203";
// Convert string to SecureString
SecureString securePassword = new SecureString();
foreach (char c in password)
{
securePassword.AppendChar(c);
}
// Display the original string and SecureString
Console.WriteLine("Original String: " + password);
DisplaySecureString(securePassword);
}
// Method to display SecureString (for demonstration purposes)
public static void DisplaySecureString(SecureString secureString)
{
IntPtr ptr = System.Runtime.InteropServices.Marshal.SecureStringToBSTR(secureString);
try
{
string plainString = System.Runtime.InteropServices.Marshal.PtrToStringBSTR(ptr);
Console.WriteLine("SecureString: " + plainString);
}
finally
{
System.Runtime.InteropServices.Marshal.ZeroFreeBSTR(ptr);
}
}
}
We have created a regular string containing the password "MySecretPassword@010203". Then, we converted this string to a SecureString using the SecureString
class.
Output:
Original String: MySecretPassword@010203
SecureString: MySecretPassword@010203
Comments (0)