Mohanapriya R Mohanapriya R
Updated date Jul 23, 2024
In this article, we will learn how to convert SecureString to String in C# while maintaining data security.

How to Convert SecureString to String in C#?

We securely convert a secureString containing the sensitive data "mySecretPassword" to a regular String. Once the conversion is done, we clear the SecureString and free the memory allocated for the BSTR pointer to maintain security.

using System;
using System.Runtime.InteropServices;
using System.Security;

class Program
{
    static void Main()
    {
        // Step 1: Create a SecureString
        SecureString secureString = new SecureString();
        string sensitiveData = "mySecretPassword";
        foreach (char c in sensitiveData)
        {
            secureString.AppendChar(c);
        }

        // Step 2: Convert SecureString to BSTR pointer
        IntPtr bstrPtr = Marshal.SecureStringToBSTR(secureString);

        // Step 3: Convert BSTR pointer to String
        string regularString = Marshal.PtrToStringBSTR(bstrPtr);

        // Output the converted String
        Console.WriteLine("Converted String: " + regularString);

        // Step 4: Clear SecureString and free memory
        secureString.Clear();
        Marshal.ZeroFreeBSTR(bstrPtr);
    }
}

Output:

Converted String: mySecretPassword

Comments (0)

There are no comments. Be the first to comment!!!