Cod*_*ist 30 c# extension-methods unsafe securestring
我需要使用SecureString微软的课程,我在互联网上找到以下代码:
public static class SecureStringExt
{
public static SecureString ConvertToSecureString(this string password)
{
if (password == null)
throw new ArgumentNullException("password");
unsafe //Red highlighted line
{
fixed (char* passwordChars = password)
{
var securePassword = new SecureString(passwordChars, password.Length);
securePassword.MakeReadOnly();
return securePassword;
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
唯一的问题是unsafe关键字一直让我错误说Cannot use unsafe construct in safe context.不幸的是我找不到为什么会这样......
注意: 上面的代码在LINQPad中运行,但在VS2013中没有(使用resharper).
myb*_*ame 10
public static SecureString GetSecureString(string password)
{
SecureString secureString = new SecureString();
foreach (char c in password)
{
secureString.AppendChar(c);
}
secureString.MakeReadOnly();
return secureString;
}
Run Code Online (Sandbox Code Playgroud)
没有不安全的代码你可以做同样的事情.