Convert String to SecureString

206,266

Solution 1

You don't. The whole reason for using the SecureString object is to avoid creating a string object (which is loaded into memory and kept there in plaintext until garbage collection). However, you can add characters to a SecureString by appending them.

var s = new SecureString();
s.AppendChar('d');
s.AppendChar('u');
s.AppendChar('m');
s.AppendChar('b');
s.AppendChar('p');
s.AppendChar('a');
s.AppendChar('s');
s.AppendChar('s');
s.AppendChar('w');
s.AppendChar('d');

Solution 2

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

Solution 3

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;
}

Solution 4

You can follow this:

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

Solution 5

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();
Share:
206,266

Related videos on Youtube

Developer404
Author by

Developer404

Independent, motivated individual with good problem solving and software development skills

Updated on July 22, 2021

Comments

  • Developer404
    Developer404 almost 3 years

    How to convert String to SecureString?

  • Developer404
    Developer404 over 14 years
    I just want to use it to set password for ProcessStartInfo and run my exe as different user.. That worked for me...
  • Mike Caron
    Mike Caron about 8 years
    This answer is an exercise is seeing how many temporary copies of the plain text can be generated in one shot
  • Ahmed Fwela
    Ahmed Fwela almost 8 years
    even fancier, no need to define a variable
  • Ahmed Fwela
    Ahmed Fwela almost 8 years
    here is a one liner : var sc = new SecureString(); foreach(char c in "foo") sc.appendChar(c);
  • Cody
    Cody over 7 years
    +1, but note that passing the password in as a string parameter creates an unencrypted string instance in managed memory and defeats the purpose of 'SecureString' in the first place. Just pointing this out for future people who come by and use this code.
  • Dan Bechard
    Dan Bechard about 7 years
    @Cody That's true, and a good point, but many of us don't care whether the SecureString is secure or not and are only using it because some Microsoft API requires it as a parameter.
  • Dan Bechard
    Dan Bechard about 7 years
    My application is secured by running it on a secure system. I couldn't care less about this particular string being encrypted in memory. There are far more vital pieces of information on this system to worry about should it ever be compromised. SecureString is simply required by a Microsoft API that my program needs to utilize. It is implied that the developer consider his or her own use-case and determine whether converting Strings to SecureStrings is a valid operation in context.
  • Dan Bechard
    Dan Bechard about 7 years
    This is the best solution by far for the most common use-case!
  • aelveborn
    aelveborn over 6 years
    This answer was posted 15 months ago. There was really no need to post it again.
  • Gian Paolo
    Gian Paolo over 6 years
    There is no point in using a SecureString if your code create a string object with the value you want to secure. The goal of SecureString is avoiding to have the string in the managed memory, so an attacker examining that memory can spot the value you want to hide. Since the NetworkCredential constructor you are calling requires a string, that's not the way to go... Sure, your code is an easy way to convert to and from a SecureString, but using it makes your code as safe as using a simple string
  • Jonathan Allen
    Jonathan Allen almost 6 years
    @GianPaolo while that is correct in theory, in practice we still need to use SecureString when working with some libraries. And lets be honest here, if someone is actively scanning the memory of your application then you've already lost. Even if you have used SecureString correctly, which I've never seen, there is going to be other valuable data to extract.
  • M.Parent
    M.Parent almost 5 years
    So this method won't prevent someone to see the password if he use a decompiler like DotPeek? Is there a way to hide strings in this case?
  • Spence
    Spence almost 5 years
    There are a few methods, depending on the threat you are trying to defeat. If it's to protect the users information from anyone but the local administrator, you can use the DPAPI methods on windows to encrypt a file and store a secret there, read it into a secure string and then throw it away. If it's for a company secret, then short answer is if your application can decrypt it, so can the user eventually.
  • user734028
    user734028 almost 5 years
    as @john-dagg suggested the idea is to NOT set a string with your password because if you do there is no advantage left to use a securestring. In your case you have put in the password in plain text, you are securing nothing by later on using a securestring. I hope you understand that the securestring was meant to secure your string from people looking at the disassembly or a debugger so see whats in the IL/memory.
  • Martin Brown
    Martin Brown almost 5 years
    @Cody Turns out that even the SecureString class can't keep the string encrypted. Which is why MS are considering obsoleting the type github.com/dotnet/platform-compat/blob/master/docs/DE0001.md‌​.
  • Eric J.
    Eric J. over 4 years
    @JonathanAllen: You're probably right, but only because we have a culture of treating security as an afterthought. If you're creating a recipe website, North Korea isn't likely to try scanning your program's memory. If you're writing banking software, the threat is much more real.
  • Roland
    Roland about 3 years
    Very useful conversion. Of course I am building secure software using SecureString for the passwords, but for compatibility with older or simpler systems we need to also support passwords in a regular string, or I will get fired :-)
  • granadaCoder
    granadaCoder almost 3 years
    Correct in an ideal world. But sometimes you have to .. have-a-string. I can code up all my (layered) code to SecureString, but when I (ultimately) make a rest call that requires a client-secret (as a plain string)......then that's what I gotta do. How I handle this is.. wait til the last possible moment to make it a string, use it, and (not really) destroy the string itself, and (try as best as I can) destroy the SecureString. it is a "best attempt" to try and minimize exposure. yes i understand the IL/memory "usage". IMHO:Microsoft should have named this object "KindaSecureString".
  • granadaCoder
    granadaCoder almost 3 years
    My previous comment is discussed here: docs.microsoft.com/en-us/dotnet/api/…. "Storage versus usage More generally, the SecureString class defines a storage mechanism for string values that should be protected or kept confidential. However, outside of the .NET Framework itself, no usage mechanism supports SecureString. This means that the secure string must be converted to a usable form (typically a clear text form) that can be recognized by its target, and that decryption and conversion must occur in user space." #cantVetoEverything
  • granadaCoder
    granadaCoder almost 3 years
    Yes, I agree. This article fragment gets into it a little. docs.microsoft.com/en-us/dotnet/api/… Storage versus usage More generally, the SecureString class defines a storage mechanism for string values that should be protected or kept confidential. However, outside of the .NET Framework itself, no usage mechanism supports SecureString. This means that the secure string must be converted to a usable form (typically a clear text form) that can be recognized by its target, and that decryption and conversion must occur in user space.
  • granadaCoder
    granadaCoder almost 3 years
    docs.microsoft.com/en-us/dotnet/api/… Overall, SecureString is more secure than String because it limits the exposure of sensitive string data. However, those strings may still be exposed to any process or operation that has access to raw memory, such as a malicious process running on the host computer, a process dump, or a user-viewable swap file. Instead of using SecureString to protect passwords, the recommended alternative is to use an opaque handle to credentials that are stored outside of the process.
  • granadaCoder
    granadaCoder almost 3 years
    But basically, you cannot "always find another way". My example would be, you have layers in your dotnet code and classes and methods where you pass around a SecureSTring.......BUT if I ultimately have to make a call to a Oauth/STS...that takes a plain string "client_secret"......at that point, I "gotta have a string". How I handle this is.. wait til the last possible moment to make it a string, use it, and (not really) destroy the string itself, and (try as best as I can) destroy the SecureString. it is a "best attempt" to try and minimize exposure. yes i understand the IL/memory "usage".
  • granadaCoder
    granadaCoder almost 3 years
    IMHO:Microsoft should have named this object "KindaSecureString". and IMHO : "#cantVetoEverything" as per the MS article "limits the exposure of sensitive string data". Aka, it limits, but is not a magic-bull3t.