Using SecureString

前端 未结 8 872
醉梦人生
醉梦人生 2020-12-24 00:56

Can this be simplified to a one liner? Feel free to completely rewrite it as long as secureString gets initialized properly.

SecureString secureString = new          


        
8条回答
  •  抹茶落季
    2020-12-24 01:23

    Since SecureString utilizes the IDispose interface. You could actually do it like this.

    SecureString secure = new SecureString();
    foreach(var character in data.ToCharArray())
        secure.AppendChar(character);
    

    Essentially the data would be a parameter.

    If you utilize the using to help alleviate resources; you'll want to be careful about the scope. But this may be a beneficial alternative, depending on usage.

    Update:

    You could actually do a full method signature:

    public static SecureString ConvertStringToSecureString(this string data)
    {
         var secure = new SecureString()
         foreach(var character in data.ToCharArray())
             secure.AppendChar(character);
    
         secure.MakeReadOnly();
         return secure;
    
    }
    

    For the decryption you would want to do:

    public static string ConvertSecureStringToString(this SecureString data)
    {
         var pointer = IntPtr.Zero;
         try
         {
              pointer = Marshal.SecureStringToGlobalAllocUnicode(data);
              return Marshal.PtrToStringUni(pointer);
         }
         finally
         {
              Marshal.ZeroFreeGlobalAllocUnicode(pointer);
         }
    }
    

    The following article will give you some additional information as well.

提交回复
热议问题