如何将 String
转换为 SecureString
?
还有一种方法可以在 SecureString
和 String
之间进行转换。
1. String to SecureString
SecureString theSecureString = new NetworkCredential("", "myPass").SecurePassword;
2. 将SecureString转换为String
string theString = new NetworkCredential("", theSecureString).Password;
这是链接
你不需要这样做。使用SecureString对象的主要原因是避免创建字符串对象(该对象会在内存中加载并以明文形式保留,直到进行垃圾收集)。但是你可以通过追加字符来向SecureString添加字符。
var s = new SecureString();
s.AppendChar('d');
s.AppendChar('u');
s.AppendChar('m');
s.AppendChar('b');
s.AppendChar('p');
s.AppendChar('a');
s.AppendChar('s');
s.AppendChar('s');
s.AppendChar('w');
s.AppendChar('d');
*****
。 - Ian BoydAppendChar
在运行时才执行,所以这些字符仍然可以从 IL 中读取,对吧?也许一些编译时的混淆能够帮上忙,如果你是在硬编码密码的话。 - samus下面的方法可帮助将字符串转换为安全字符串
private SecureString ConvertToSecureString(string password)
{
if (password == null)
throw new ArgumentNullException("password");
var securePassword = new SecureString();
foreach (char c in password)
securePassword.AppendChar(c);
securePassword.MakeReadOnly();
return securePassword;
}
你可以按照以下步骤进行:
string password = "test";
SecureString sec_pass = new SecureString();
Array.ForEach(password.ToArray(), sec_pass.AppendChar);
sec_pass.MakeReadOnly();
这里有一个简单的 LINQ 技巧。
SecureString sec = new SecureString();
string pwd = "abc123"; /* Not Secure! */
pwd.ToCharArray().ToList().ForEach(sec.AppendChar);
/* and now : seal the deal */
sec.MakeReadOnly();
我想提出一些看法。为什么呢?
你不能仅仅将所有字符串更改为安全字符串,然后突然间使你的应用程序“安全”了。安全字符串的设计目的是尽可能地保持字符串加密,并只在非常短的时间内进行解密,在操作完成后会清除存储器。
我认为,在担心保护应用程序字符串之前,您可能需要解决一些设计层面上的问题。请给我们更多关于您正在尝试做什么的信息,我们也许能够更好地帮助您。
unsafe
{
fixed(char* psz = password)
return new SecureString(psz, password.Length);
}
不需要花哨的Linq,也不需要手动添加所有字符,只需要简单明了:
var str = "foo";
var sc = new SecureString();
foreach(char c in str) sc.appendChar(c);
var sc = new SecureString(); foreach(char c in "foo") sc.appendChar(c);
- Ahmed FwelaFor a char
array
public static SecureString ToSecureString(this char[] _self)
{
SecureString knox = new SecureString();
foreach (char c in _self)
{
knox.AppendChar(c);
}
return knox;
}
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;
}
AppendChar
建议。
string
对象,那么使用SecureString
就没有意义了。SecureString
的目标是避免在托管内存中拥有字符串,因此,攻击者检查该内存时可以发现您要隐藏的值。由于您调用的NetworkCredential
构造函数需要一个字符串,所以这不是正确的方法... 当然,您的代码是将SecureString
转换成string
和反之的简单方法,但使用它使得您的代码与使用简单的string
一样安全。 - Gian Paolo