PasswordDeriveBytes Classe

Definição

Deriva uma chave de uma senha usando uma extensão do algoritmo PBKDF1.

public ref class PasswordDeriveBytes : System::Security::Cryptography::DeriveBytes
public class PasswordDeriveBytes : System.Security.Cryptography.DeriveBytes
[System.Runtime.InteropServices.ComVisible(true)]
public class PasswordDeriveBytes : System.Security.Cryptography.DeriveBytes
type PasswordDeriveBytes = class
    inherit DeriveBytes
[<System.Runtime.InteropServices.ComVisible(true)>]
type PasswordDeriveBytes = class
    inherit DeriveBytes
Public Class PasswordDeriveBytes
Inherits DeriveBytes
Herança
PasswordDeriveBytes
Atributos

Exemplos

O exemplo de código a seguir cria uma chave de uma senha usando a PasswordDeriveBytes classe.

using System;
using System.Security.Cryptography;
using System.Text;

public class PasswordDerivedBytesExample
{

    public static void Main(String[] args)
    {

        // Get a password from the user.
        Console.WriteLine("Enter a password to produce a key:");

        byte[] pwd = Encoding.Unicode.GetBytes(Console.ReadLine());

        byte[] salt = CreateRandomSalt(7);

        // Create a TripleDESCryptoServiceProvider object.
        TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();

        try
        {
            Console.WriteLine("Creating a key with PasswordDeriveBytes...");

            // Create a PasswordDeriveBytes object and then create
            // a TripleDES key from the password and salt.
            PasswordDeriveBytes pdb = new PasswordDeriveBytes(pwd, salt);


            // Create the key and set it to the Key property
            // of the TripleDESCryptoServiceProvider object.
            // This example uses the SHA1 algorithm.
            // Due to collision problems with SHA1, Microsoft recommends SHA256 or better.
            tdes.Key = pdb.CryptDeriveKey("TripleDES", "SHA1", 192, tdes.IV);


            Console.WriteLine("Operation complete.");
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }
        finally
        {
            // Clear the buffers
            ClearBytes(pwd);
            ClearBytes(salt);

            // Clear the key.
            tdes.Clear();
        }

        Console.ReadLine();
    }

    //////////////////////////////////////////////////////////
    // Helper methods:
    // CreateRandomSalt: Generates a random salt value of the
    //                   specified length.
    //
    // ClearBytes: Clear the bytes in a buffer so they can't
    //             later be read from memory.
    //////////////////////////////////////////////////////////

    public static byte[] CreateRandomSalt(int length)
    {
        // Create a buffer
        byte[] randBytes;

        if (length >= 1)
        {
            randBytes = new byte[length];
        }
        else
        {
            randBytes = new byte[1];
        }

        using (RandomNumberGenerator rng = RandomNumberGenerator.Create())
        {
            // Fill the buffer with random bytes.
            rng.GetBytes(randBytes);
        }

        // return the bytes.
        return randBytes;
    }

    public static void ClearBytes(byte[] buffer)
    {
        // Check arguments.
        if (buffer == null)
        {
            throw new ArgumentException("buffer");
        }

        // Set each byte in the buffer to 0.
        for (int x = 0; x < buffer.Length; x++)
        {
            buffer[x] = 0;
        }
    }
}
Imports System.Security.Cryptography
Imports System.Text



Module PasswordDerivedBytesExample


    Sub Main(ByVal args() As String)

        ' Get a password from the user.
        Console.WriteLine("Enter a password to produce a key:")

        Dim pwd As Byte() = Encoding.Unicode.GetBytes(Console.ReadLine())

        Dim salt As Byte() = CreateRandomSalt(7)

        ' Create a TripleDESCryptoServiceProvider object.
        Dim tdes As New TripleDESCryptoServiceProvider()

        Try
            Console.WriteLine("Creating a key with PasswordDeriveBytes...")

            ' Create a PasswordDeriveBytes object and then create 
            ' a TripleDES key from the password and salt.
            Dim pdb As New PasswordDeriveBytes(pwd, salt)


            ' Create the key and set it to the Key property
            ' of the TripleDESCryptoServiceProvider object.
            ' This example uses the SHA1 algorithm.
            ' Due to collision problems with SHA1, Microsoft recommends SHA256 or better.
            tdes.Key = pdb.CryptDeriveKey("TripleDES", "SHA1", 192, tdes.IV)


            Console.WriteLine("Operation complete.")
        Catch e As Exception
            Console.WriteLine(e.Message)
        Finally
            ' Clear the buffers
            ClearBytes(pwd)
            ClearBytes(salt)

            ' Clear the key.
            tdes.Clear()
        End Try

        Console.ReadLine()

    End Sub


    '********************************************************
    '* Helper methods:
    '* createRandomSalt: Generates a random salt value of the 
    '*                   specified length.  
    '*
    '* clearBytes: Clear the bytes in a buffer so they can't 
    '*             later be read from memory.
    '********************************************************
    Function CreateRandomSalt(ByVal length As Integer) As Byte()
        ' Create a buffer
        Dim randBytes() As Byte

        If length >= 1 Then
            randBytes = New Byte(length) {}
        Else
            randBytes = New Byte(0) {}
        End If

        ' Create a new RandomNumberGenerator.
        Using rand As RandomNumberGenerator = RandomNumberGenerator.Create()
            ' Fill the buffer with random bytes.
            rand.GetBytes(randBytes)
        End Using

        ' return the bytes.
        Return randBytes

    End Function


    Sub ClearBytes(ByVal buffer() As Byte)
        ' Check arguments.
        If buffer Is Nothing Then
            Throw New ArgumentException("buffer")
        End If

        ' Set each byte in the buffer to 0.
        Dim x As Integer
        For x = 0 To buffer.Length - 1
            buffer(x) = 0
        Next x

    End Sub
End Module

Comentários

Essa classe usa uma extensão do algoritmo PBKDF1 definido no padrão PKCS nº 5 v2.0 para derivar bytes adequados para uso como material de chave de uma senha. O padrão está documentado no IETF RRC 2898.

Importante

Nunca codifique uma senha no código-fonte. Senhas codificadas em código podem ser recuperadas de um assembly usando a ferramenta Ildasm.exe (IL Disassembler), um editor hex ou simplesmente abrindo o assembly em um editor de texto como notepad.exe.

Construtores

Nome Description
PasswordDeriveBytes(Byte[], Byte[], CspParameters)

Inicializa uma nova instância da PasswordDeriveBytes classe que especifica a senha, o sal de chaves e o CSP (provedor de serviços criptográficos) a serem usados para derivar a chave.

PasswordDeriveBytes(Byte[], Byte[], String, Int32, CspParameters)

Inicializa uma nova instância da PasswordDeriveBytes classe que especifica a senha, o sal da chave, o nome do hash, as iterações e o CSP (provedor de serviços criptográficos) a serem usados para derivar a chave.

PasswordDeriveBytes(Byte[], Byte[], String, Int32)

Inicializa uma nova instância da PasswordDeriveBytes classe especificando a senha, o sal da chave, o nome do hash e as iterações a serem usadas para derivar a chave.

PasswordDeriveBytes(Byte[], Byte[])

Inicializa uma nova instância da PasswordDeriveBytes classe especificando a senha e o sal de chaves a serem usados para derivar a chave.

PasswordDeriveBytes(String, Byte[], CspParameters)

Inicializa uma nova instância da PasswordDeriveBytes classe com os parâmetros de senha, sal de chave e CSP (provedor de serviços criptográficos) a serem usados para derivar a chave.

PasswordDeriveBytes(String, Byte[], String, Int32, CspParameters)

Inicializa uma nova instância da PasswordDeriveBytes classe com a senha, o sal da chave, o nome do hash, o número de iterações e os parâmetros do CSP (provedor de serviços criptográficos) a serem usados para derivar a chave.

PasswordDeriveBytes(String, Byte[], String, Int32)

Inicializa uma nova instância da PasswordDeriveBytes classe com a senha, o sal da chave, o nome do hash e o número de iterações a serem usadas para derivar a chave.

PasswordDeriveBytes(String, Byte[])

Inicializa uma nova instância da PasswordDeriveBytes classe com a senha e o sal de chave a serem usados para derivar a chave.

Propriedades

Nome Description
HashName

Obtém ou define o nome do algoritmo de hash para a operação.

IterationCount

Obtém ou define o número de iterações para a operação.

Salt

Obtém ou define o valor de sal da chave para a operação.

Métodos

Nome Description
CryptDeriveKey(String, String, Int32, Byte[])

Deriva uma chave criptográfica do PasswordDeriveBytes objeto.

Dispose()

Quando substituído em uma classe derivada, libera todos os recursos usados pela instância atual da DeriveBytes classe.

(Herdado de DeriveBytes)
Dispose(Boolean)

Libera os recursos não gerenciados usados pela PasswordDeriveBytes classe e, opcionalmente, libera os recursos gerenciados.

Equals(Object)

Determina se o objeto especificado é igual ao objeto atual.

(Herdado de Object)
Finalize()

Permite que um objeto tente liberar recursos e executar outras operações de limpeza antes de ser recuperado pela coleta de lixo.

GetBytes(Int32)
Obsoleto.

Retorna bytes pseudo-aleatórios de chave.

GetHashCode()

Serve como a função hash predefinida.

(Herdado de Object)
GetType()

Obtém o Type da instância atual.

(Herdado de Object)
MemberwiseClone()

Cria uma cópia superficial do Objectatual.

(Herdado de Object)
Reset()

Redefine o estado da operação.

ToString()

Retorna uma cadeia de caracteres que representa o objeto atual.

(Herdado de Object)

Aplica-se a

Confira também