我想在VB.NET中使用SecureString变量并将其转换为SHA1或SHA512哈希。我如何安全地将SecureString转换为HashAlgorithm.ComputeHash将接受的Byte数组?
答案 0 :(得分:0)
如果我们避免使用唯一的String实例(输出)并将其替换为字符数组,那该怎么办呢?这将使我们能够在使用后擦除此数组:
public static String SecureStringToMD5( SecureString password )
{
int passwordLength = password.Length;
char[] passwordChars = new char[passwordLength];
// Copy the password from SecureString to our char array
IntPtr passwortPointer = Marshal.SecureStringToBSTR( password );
Marshal.Copy( passwortPointer, passwordChars, 0, passwordLength );
Marshal.ZeroFreeBSTR( passwortPointer );
// Hash the char array
MD5 md5Hasher = MD5.Create();
byte[] hashedPasswordBytes = md5Hasher.ComputeHash( Encoding.Default.GetBytes( passwordChars ) );
// Wipe the character array from memory
for (int i = 0; i < passwordChars.Length; i++)
{
passwordChars[i] = '\0';
}
// Your implementation of representing the hash in a readable manner
String hashString = ConvertToHexString( hashedPasswordBytes );
// Return the result
return hashString;
}
我错过了什么吗?
答案 1 :(得分:-2)
在c#中输入并转换为VB。希望它仍然有用!
Dim input As [Char]() = "Super Secret String".ToCharArray()
Dim secret As New SecureString()
For idx As Integer = 0 To input.Length - 1
secret.AppendChar(input(idx))
Next
SecurePassword.MakeReadOnly()
Dim pBStr As IntPtr = Marshal.SecureStringToBSTR(secret)
Dim output As String = Marshal.PtrToStringBSTR(pBStr)
Marshal.FreeBSTR(pBStr)
Dim sha As SHA512 = New SHA512Managed()
Dim result As Byte() = sha.ComputeHash(Encoding.UTF8.GetBytes(output))
修改:
正如我和其他几位评论中所指出的那样,我想在此引起关注。这样做不是一个好主意。您正在将字节移动到不再安全的位置。当然你可以做到,但你可能不应该