Compartilhar via


Método Marshal.SecureStringToCoTaskMemAnsi (SecureString)

 

Dica

The .NET API Reference documentation has a new home. Visit the .NET API Browser on docs.microsoft.com to see the new experience.

Copia o conteúdo de um objeto SecureString gerenciado para um bloco de memória alocado do alocador de tarefas COM não gerenciado.

Namespace:   System.Runtime.InteropServices
Assembly:  mscorlib (em mscorlib.dll)

Sintaxe

[SecurityCriticalAttribute]
public static IntPtr SecureStringToCoTaskMemAnsi(
    SecureString s
)
public:
[SecurityCriticalAttribute]
static IntPtr SecureStringToCoTaskMemAnsi(
    SecureString^ s
)
[<SecurityCriticalAttribute>]
static member SecureStringToCoTaskMemAnsi : 
        s:SecureString -> nativeint
<SecurityCriticalAttribute>
Public Shared Function SecureStringToCoTaskMemAnsi (
    s As SecureString
) As IntPtr

Parâmetros

Valor Retornado

Type: System.IntPtr

O endereço, na memória não gerenciada, para o qual o parâmetro s foi copiado ou 0 se um objeto nulo foi fornecido.

Exceções

Exception Condition
ArgumentNullException

O parâmetro s é null.

NotSupportedException

O computador atual não está executando o Windows 2000 Service Pack 3 ou posterior.

OutOfMemoryException

Não há memória suficiente disponível.

Comentários

O SecureStringToCoTaskMemAnsi método é útil para empacotamento personalizado ou ao misturar gerenciado e código não gerenciado. Como esse método aloca a memória não gerenciada, necessária para uma cadeia de caracteres, sempre liberar a memória chamando ZeroFreeCoTaskMemAnsi. Os caracteres da cadeia de caracteres são copiados como caracteres ANSI.

Observações para os Autores de Chamada:

Esse método é suportada apenas em computadores que executam o Windows 2000 Service Pack 3 ou posterior.

Exemplos

O exemplo a seguir usa o SecureStringToCoTaskMemAnsi método para empacotar e descriptografar o conteúdo de um SecureString objeto para um bloco de memória não gerenciada. Ele usa o ZeroFreeCoTaskMemAnsi método para zerar e descartar o bloco não gerenciado.

using System;
using System.Runtime.InteropServices;
using System.Security;

class MarshalExample
{
     static void Main()
     {
         IntPtr unmanagedRef = IntPtr.Zero;

          // Ask the user for a password.
          Console.Write("Please enter your password: ");

          SecureString passWord = GetPassword();

          Console.WriteLine("Copying and decrypting the string to unmanaged memory...");

          // Copy the Secure string to unmanaged memory (and decrypt it).
          unmanagedRef = Marshal.SecureStringToCoTaskMemAnsi(passWord);

          if (unmanagedRef != IntPtr.Zero)
          {
              Console.WriteLine("Zeroing out unmanaged memory...");

              Marshal.ZeroFreeCoTaskMemAnsi(unmanagedRef);
          }
          passWord.Dispose();

         Console.WriteLine("Done.");
     }

     public static SecureString GetPassword()
     {
         SecureString password = new SecureString();

         // get the first character of the password
         ConsoleKeyInfo nextKey = Console.ReadKey(true);

         while (nextKey.Key != ConsoleKey.Enter)
         {
             if (nextKey.Key == ConsoleKey.Backspace)
             {
                 if (password.Length > 0)
                 {
                     password.RemoveAt(password.Length - 1);

                     // erase the last * as well
                     Console.Write(nextKey.KeyChar);
                     Console.Write(" ");
                     Console.Write(nextKey.KeyChar);
                 }
             }
             else
             {
                 password.AppendChar(nextKey.KeyChar);
                 Console.Write("*");
             }

             nextKey = Console.ReadKey(true);
         }

         Console.WriteLine();

         // lock the password down
         password.MakeReadOnly();
         return password;
     }
}
Imports System.Runtime.InteropServices
Imports System.Security

Module Example
    Sub Main()
        Dim unmanagedRef As IntPtr

         ' Ask the user for a password.
         Console.Write("Please enter your password: ")
         Dim passWord As SecureString = GetPassword()

         Console.WriteLine("Copying and decrypting the string to unmanaged memory...")

         ' Copy the Secure string to unmanaged memory (and decrypt it).
         unmanagedRef = Marshal.SecureStringToCoTaskMemAnsi(passWord)

         If unmanagedRef <> IntPtr.Size Then
             Console.WriteLine("Zeroing out unmanaged memory...")
             Marshal.ZeroFreeCoTaskMemAnsi(unmanagedRef)
         End If
         passWord.Dispose()

        Console.WriteLine("Done.")
    End Sub



    Function GetPassword() As SecureString
        Dim password As New SecureString()

        ' get the first character of the password
        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

        Console.WriteLine()

        ' lock the password down
        password.MakeReadOnly()
        Return password

    End Function
End Module

Segurança

SecurityCriticalAttribute

requires full trust for the immediate caller. This member cannot be used by partially trusted or transparent code.

Informações de Versão

.NET Framework
Disponível desde 2.0

Confira Também

Classe Marshal
Namespace System.Runtime.InteropServices

Retornar ao início