[VB.NET]SecureString較為安全的加密字串類別
Public Sub PrintSecureString(ByVal secureString As SecureString)
...
End Sub</pre></div>
Module Module1
Sub Main()
Console.WriteLine("Please enter your password to be encrypted:")
Dim password As SecureString = ReadPassword()
Console.WriteLine()
Console.WriteLine("Decripted password:")
PrintPassword(password)
End Sub
Public Function ReadPassword() As SecureString
Dim password As New SecureString()
Dim nextKey As ConsoleKeyInfo = Console.ReadKey(True)
While nextKey.Key <> ConsoleKey.Enter
If nextKey.Key = ConsoleKey.Backspace Then
If password.Length > 0 Then
password.RemoveAt(password.Length - 1)
' erase the last * as well
Console.Write(nextKey.KeyChar)
Console.Write(" ")
Console.Write(nextKey.KeyChar)
End If
Else
password.AppendChar(nextKey.KeyChar)
Console.Write("*")
End If
nextKey = Console.ReadKey(True)
End While
password.MakeReadOnly()
' make the password read-only.
' return the encrypted password.
Return password
End Function
Public Sub PrintPassword(ByVal password As SecureString)
' Uncrypt the password and get a reference to it...
Dim bstr As IntPtr = Marshal.SecureStringToBSTR(password)
Try
' Printing the uncrypted password...
Console.WriteLine(Marshal.PtrToStringBSTR(bstr))
Finally
Marshal.ZeroFreeBSTR(bstr)
End Try
End Sub
End Module