Compartilhar via


Método Marshal.SecureStringToCoTaskMemUnicode (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 SecureStringToCoTaskMemUnicode(
    SecureString s
)
public:
[SecurityCriticalAttribute]
static IntPtr SecureStringToCoTaskMemUnicode(
    SecureString^ s
)
[<SecurityCriticalAttribute>]
static member SecureStringToCoTaskMemUnicode : 
        s:SecureString -> nativeint
<SecurityCriticalAttribute>
Public Shared Function SecureStringToCoTaskMemUnicode (
    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 SecureStringToCoTaskMemUnicode 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 o ZeroFreeCoTaskMemUnicode método. Os caracteres da cadeia de caracteres são copiados como caracteres Unicode.

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 SecureStringToCoTaskMemUnicode 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 ZeroFreeCoTaskMemUnicode método para zerar e descartar o bloco não gerenciado.

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

class Example
{
    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.SecureStringToCoTaskMemUnicode(passWord);
        passWord.Dispose();

        if (unmanagedRef != IntPtr.Zero) {
            Console.WriteLine("Zeroing out unmanaged memory...");
            Marshal.ZeroFreeCoTaskMemUnicode(unmanagedRef);
        }
        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;
     }
 }
// The example displays output like the following:
//       Please enter your password: **********
//       Copying and decrypting the string to unmanaged memory...
//       Zeroing out unmanaged memory...
//       Done.
Imports System.Runtime.InteropServices
Imports System.Security

Module Example
    Public 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.SecureStringToCoTaskMemUnicode(passWord)
        passWord.Dispose()

        If unmanagedRef <> IntPtr.Size Then
            Console.WriteLine("Zeroing out unmanaged memory...")
            Marshal.ZeroFreeCoTaskMemUnicode(unmanagedRef)
        End If
        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
' The example displays output like the following:
'       Please enter your password: **********
'       Copying and decrypting the string to unmanaged memory...
'       Zeroing out unmanaged memory...
'       Done.

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