PasswordDeriveBytes Classe

Definição

Deriva uma chave a partir de uma palavra-passe 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 seguinte cria uma chave a partir de uma palavra-passe 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

Observações

Esta classe utiliza uma extensão do algoritmo PBKDF1 definido no padrão PKCS#5 v2.0 para derivar bytes adequados para uso como material chave a partir de uma palavra-passe. A norma está documentada no IETF RRC 2898.

Importante

Nunca codifique uma palavra-passe no seu código-fonte. As palavras-passe codificadas de forma rígida podem ser recuperadas de um assembly usando a ferramenta Ildasm.exe (IL Disassembler), um editor hexadecimal ou simplesmente abrindo o assembly num editor de texto como notepad.exe.

Construtores

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

Inicializa uma nova instância da PasswordDeriveBytes classe que especifica a palavra-passe, o key salt e o fornecedor de serviços criptográficos (CSP) a usar para obter a chave.

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

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

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

Inicializa uma nova instância da PasswordDeriveBytes classe especificando a palavra-passe, o sal da chave, o nome do hash e as iterações a usar para derivar a chave.

PasswordDeriveBytes(Byte[], Byte[])

Inicializa uma nova instância da PasswordDeriveBytes classe que especifica a palavra-passe e o sal da chave a usar para obter a chave.

PasswordDeriveBytes(String, Byte[], CspParameters)

Inicializa uma nova instância da PasswordDeriveBytes classe com os parâmetros password, key salt e fornecedor de serviços criptográficos (CSP) para usar para derivar a chave.

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

Inicializa uma nova instância da PasswordDeriveBytes classe com a palavra-passe, sal da chave, nome do hash, número de iterações e parâmetros do fornecedor de serviços criptográficos (CSP) a usar para derivar a chave.

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

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

PasswordDeriveBytes(String, Byte[])

Inicializa uma nova instância da PasswordDeriveBytes classe com a palavra-passe e o sal da chave para usar para obter a chave.

Propriedades

Name 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 chave de sal para a operação.

Métodos

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

Deriva uma chave criptográfica a partir do PasswordDeriveBytes objeto.

Dispose()

Quando é sobreposto numa classe derivada, liberta todos os recursos usados pela instância atual da DeriveBytes classe.

(Herdado de DeriveBytes)
Dispose(Boolean)

Liberta os recursos não geridos usados pela PasswordDeriveBytes classe e, opcionalmente, liberta os recursos geridos.

Equals(Object)

Determina se o objeto especificado é igual ao objeto atual.

(Herdado de Object)
Finalize()

Permite que um objeto tente libertar recursos e realizar outras operações de limpeza antes de ser recuperado pela recolha de lixo.

GetBytes(Int32)
Obsoleto.

Devolve bytes de chave pseudo-aleatórios.

GetHashCode()

Serve como função de hash predefinida.

(Herdado de Object)
GetType()

Obtém o Type da instância atual.

(Herdado de Object)
MemberwiseClone()

Cria uma cópia superficial do atual Object.

(Herdado de Object)
Reset()

Reinicia o estado da operação.

ToString()

Devolve uma cadeia que representa o objeto atual.

(Herdado de Object)

Aplica-se a

Ver também