securestring

which is better code?  http://social.msdn.microsoft.com/Forums/zh-CN/csharpgeneral/thread/9c213851-7ee3-4bee-b811-255950138aad

1.)

public static string ConvertToUnsecureString(this SecureString securePassword)
{
    if (securePassword == null)
        throw new ArgumentNullException("securePassword");

    IntPtr unmanagedString = IntPtr.Zero;
    try
    {
        unmanagedString = Marshal.SecureStringToGlobalAllocUnicode(securePassword);
        return Marshal.PtrToStringUni(unmanagedString);
    }
    finally
    {
        Marshal.ZeroFreeGlobalAllocUnicode(unmanagedString);
    }
}



2.

internal static string Password

{

get

{

if (_useCurrentCredentials)

{

return string.Empty;

}

char[] bytes = new char[_userPassword.Length];

IntPtr ptr = IntPtr.Zero;

try

{

ptr = Marshal.SecureStringToBSTR(_userPassword);

bytes = new char[_userPassword.Length];

Marshal.Copy(ptr, bytes, 0, _userPassword.Length);

}

finally

{

if (ptr != IntPtr.Zero)

Marshal.ZeroFreeBSTR(ptr);

}

return new string(bytes);

}

}


and now, which is the better code??

1.)

public static SecureString ConvertToSecureString(this string password)
{
    if (password == null)
        throw new ArgumentNullException("password");

    unsafe
    {
        fixed (char* passwordChars = password)
        {
            var securePassword = new SecureString(passwordChars, password.Length);
            securePassword.MakeReadOnly();
            return securePassword;
        }
    }
}



2.)

 private static void ReadPassword(string pwd)
        {
            _userPassword = new SecureString();
            foreach (char c in pwd)
            {
                _userPassword.AppendChar(c);
            }
            _userPassword.MakeReadOnly();
        }




In both cases I think it's mostly a matter of style, the end result is the same and one isn't significantly better than the other.

In the first question, in #1 might be slightly better from a memory use point of view since you avoid allocating an intermediary char[].

In the second question, note that the SecureString(char*, int) constructor is documented as "This API supports the .NET Framework infrastructure and is not intended to be used directly from your code".

原文地址:https://www.cnblogs.com/junkai/p/2672412.html