[c#] Convert String to SecureString

How to convert String to SecureString?

This question is related to c# .net security securestring

The answer is


You can follow this:

string password = "test";
SecureString sec_pass = new SecureString();
Array.ForEach(password.ToArray(), sec_pass.AppendChar);
sec_pass.MakeReadOnly();

If you would like to compress the conversion of a string to a SecureString into a LINQ statement you can express it as follows:

var plain  = "The quick brown fox jumps over the lazy dog";
var secure = plain
             .ToCharArray()
             .Aggregate( new SecureString()
                       , (s, c) => { s.AppendChar(c); return s; }
                       , (s)    => { s.MakeReadOnly(); return s; }
                       );

However, keep in mind that using LINQ does not improve the security of this solution. It suffers from the same flaw as any conversion from string to SecureString. As long as the original string remains in memory the data is vulnerable.

That being said, what the above statement can offer is keeping together the creation of the SecureString, its initialization with data and finally locking it from modification.


unsafe 
{
    fixed(char* psz = password)
        return new SecureString(psz, password.Length);
}

below method helps to convert string to secure string

private SecureString ConvertToSecureString(string password)
{
    if (password == null)
        throw new ArgumentNullException("password");

    var securePassword = new SecureString();

    foreach (char c in password)
        securePassword.AppendChar(c);

    securePassword.MakeReadOnly();
    return securePassword;
}

I'm agree with Spence (+1), but if you're doing it for learning or testing pourposes, you can use a foreach in the string, appending each char to the securestring using the AppendChar method.


you can use this simple script

private SecureString SecureStringConverter(string pass)
{
    SecureString ret = new SecureString();

    foreach (char chr in pass.ToCharArray())
        ret.AppendChar(chr);

    return ret;
}

The following 2 extensions should do the trick:

  1. For a char array

    public static SecureString ToSecureString(this char[] _self)
    {
        SecureString knox = new SecureString();
        foreach (char c in _self)
        {
            knox.AppendChar(c);
        }
        return knox;
    }
    
  2. And for string

    public static SecureString ToSecureString(this string _self)
    {
        SecureString knox = new SecureString();
        char[] chars = _self.ToCharArray();
        foreach (char c in chars)
        {
            knox.AppendChar(c);
        }
        return knox;
    }
    

Thanks to John Dagg for the AppendChar recommendation.


I'll throw this out there. Why?

You can't just change all your strings to secure strings and suddenly your application is "secure". Secure string is designed to keep the string encrypted for as long as possible, and only decrypted for a very short period of time, wiping the memory after an operation has been performed upon it.

I would hazard saying that you may have some design level issues to deal with before worrying about securing your application strings. Give us some more information on what your trying to do and we may be able to help better.


Here is a cheap linq trick.

            SecureString sec = new SecureString();
            string pwd = "abc123"; /* Not Secure! */
            pwd.ToCharArray().ToList().ForEach(sec.AppendChar);
            /* and now : seal the deal */
            sec.MakeReadOnly();

no fancy linq, not adding all the chars by hand, just plain and simple:

var str = "foo";
var sc = new SecureString();
foreach(char c in str) sc.appendChar(c);

There is also another way to convert between SecureString and String.

1. String to SecureString

SecureString theSecureString = new NetworkCredential("", "myPass").SecurePassword;

2. SecureString to String

string theString = new NetworkCredential("", theSecureString).Password;

Here is the link


I just want to point out to all the people saying, "That's not the point of SecureString", that many of the people asking this question might be in an application where, for whatever reason, justified or not, they are not particularly concerned about having a temporary copy of the password sit on the heap as a GC-able string, but they have to use an API that only accepts SecureString objects. So, you have an app where you don't care whether the password is on the heap, maybe it's internal-use only and the password is only there because it's required by the underlying network protocols, and you find that that string where the password is stored cannot be used to e.g. set up a remote PowerShell Runspace -- but there is no easy, straight-forward one-liner to create that SecureString that you need. It's a minor inconvenience -- but probably worth it to ensure that the applications that really do need SecureString don't tempt the authors to use System.String or System.Char[] intermediaries. :-)


Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to .net

You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to use Bootstrap 4 in ASP.NET Core No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization .net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible Update .NET web service to use TLS 1.2 EF Core add-migration Build Failed What is the difference between .NET Core and .NET Standard Class Library project types? Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=4.1.0.0' or one of its dependencies Nuget connection attempt failed "Unable to load the service index for source" Token based authentication in Web API without any user interface

Examples related to security

Monitoring the Full Disclosure mailinglist Two Page Login with Spring Security 3.2.x How to prevent a browser from storing passwords JWT authentication for ASP.NET Web API How to use a client certificate to authenticate and authorize in a Web API Disable-web-security in Chrome 48+ When you use 'badidea' or 'thisisunsafe' to bypass a Chrome certificate/HSTS error, does it only apply for the current site? How does Content Security Policy (CSP) work? How to prevent Screen Capture in Android Default SecurityProtocol in .NET 4.5

Examples related to securestring

Convert a secure string to plain text Secure random token in Node.js Convert String to SecureString