Convert String to SecureString

前端 未结 13 1789
粉色の甜心
粉色の甜心 2020-12-12 15:43

How to convert String to SecureString?

相关标签:
13条回答
  • 2020-12-12 16:19

    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.

    0 讨论(0)
  • 2020-12-12 16:21

    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);
    
    0 讨论(0)
  • 2020-12-12 16:24

    You can follow this:

    string password = "test";
    SecureString sec_pass = new SecureString();
    Array.ForEach(password.ToArray(), sec_pass.AppendChar);
    sec_pass.MakeReadOnly();
    
    0 讨论(0)
  • 2020-12-12 16:28

    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();
    
    0 讨论(0)
  • 2020-12-12 16:29

    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.

    0 讨论(0)
  • 2020-12-12 16:33
    unsafe 
    {
        fixed(char* psz = password)
            return new SecureString(psz, password.Length);
    }
    
    0 讨论(0)
提交回复
热议问题