Convert String to SecureString

2020-02-07 15:58发布

How to convert String to SecureString?

13条回答
▲ chillily
2楼-- · 2020-02-07 16:59

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();
查看更多
劫难
3楼-- · 2020-02-07 17:01

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

查看更多
别忘想泡老子
4楼-- · 2020-02-07 17:01
unsafe 
{
    fixed(char* psz = password)
        return new SecureString(psz, password.Length);
}
查看更多
劳资没心,怎么记你
5楼-- · 2020-02-07 17:02

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.

查看更多
The star\"
6楼-- · 2020-02-07 17:03

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.

查看更多
唯我独甜
7楼-- · 2020-02-07 17:04

You can follow this:

string password = "test";
SecureString sec_pass = new SecureString();
Array.ForEach(password.ToArray(), sec_pass.AppendChar);
sec_pass.MakeReadOnly();
查看更多
登录 后发表回答