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/archive/2012/09/05/2672412.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值