共用方式為


PasswordDeriveBytes 類別

定義

使用 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
繼承
PasswordDeriveBytes
屬性

範例

下列程式代碼範例會使用 PasswordDeriveBytes 類別,從密碼建立密鑰。

using namespace System;
using namespace System::Security::Cryptography;
using namespace System::Text;

// Generates a random salt value of the specified length.
array<Byte>^ CreateRandomSalt(int length)
{
    // Create a buffer
    array<Byte>^ randomBytes;

    if (length >= 1)
    {
        randomBytes = gcnew array <Byte>(length);
    }
    else
    {
        randomBytes = gcnew array <Byte>(1);
    }

    // Create a new RNGCryptoServiceProvider.
    RNGCryptoServiceProvider^ cryptoRNGProvider =
        gcnew RNGCryptoServiceProvider();

    // Fill the buffer with random bytes.
    cryptoRNGProvider->GetBytes(randomBytes);

    // return the bytes.
    return randomBytes;
}

// Clears the bytes in a buffer so they can't later be read from memory.
void ClearBytes(array<Byte>^ buffer)
{
    // Check arguments.
    if (buffer == nullptr)
    {
        throw gcnew ArgumentNullException("buffer");
    }

    // Set each byte in the buffer to 0.
    for (int x = 0; x <= buffer->Length - 1; x++)
    {
        buffer[x] = 0;
    }
}

int main(array<String^>^ args)
{

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

    // Security Note: Never hard-code a password within your
    // source code.  Hard-coded passwords can be retrieved
    // from a compiled assembly.
    array<Byte>^ password = Encoding::Unicode->GetBytes(Console::ReadLine());

    array<Byte>^ randomSalt = CreateRandomSalt(7);

    // Create a TripleDESCryptoServiceProvider object.
    TripleDESCryptoServiceProvider^ cryptoDESProvider =
        gcnew 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^ passwordDeriveBytes = gcnew PasswordDeriveBytes
            (password->ToString(), randomSalt);

       // 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.
        cryptoDESProvider->Key = passwordDeriveBytes->CryptDeriveKey
            ("TripleDES", "SHA1", 192, cryptoDESProvider->IV);
        Console::WriteLine("Operation complete.");
    }
    catch (Exception^ ex)
    {
        Console::WriteLine(ex->Message);
    }
    finally
    {
        // Clear the buffers
        ClearBytes(password);
        ClearBytes(randomSalt);

        // Clear the key.
        cryptoDESProvider->Clear();
    }

    Console::ReadLine();
}
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];
        }

        // Create a new RNGCryptoServiceProvider.
        RNGCryptoServiceProvider rand = new RNGCryptoServiceProvider();

        // Fill the buffer with random bytes.
        rand.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 RNGCryptoServiceProvider.
        Dim rand As New RNGCryptoServiceProvider()

        ' Fill the buffer with random bytes.
        rand.GetBytes(randBytes)

        ' 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

備註

這個類別會使用 PKCS#5 v2.0 標準中定義的 PBKDF1 演算法延伸,衍生適合用來作為密碼密鑰數據的位元組。 標準記載於 IETF RRC 2898 中。

重要

絕對不要在原始程式碼中硬式編碼密碼。 硬式編碼密碼可以從元件擷取,方法是使用 Ildasm.exe (IL 反組譯程式) 工具、十六進位編輯器,或在文本編輯器中開啟元件,例如 notepad.exe。

建構函式

PasswordDeriveBytes(Byte[], Byte[])

指定用來衍生金鑰的密碼和金鑰 Salt,初始化 PasswordDeriveBytes 類別的新執行個體。

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

指定用來衍生金鑰的密碼、金鑰 Salt 和密碼編譯服務提供者 (CSP),初始化 PasswordDeriveBytes 類別的新執行個體。

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

指定用來衍生金鑰的密碼、金鑰 Salt、雜湊名稱和反覆運算,初始化 PasswordDeriveBytes 類別的新執行個體。

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

指定用來衍生金鑰的密碼、金鑰 Salt、雜湊名稱、反覆運算和密碼編譯服務提供者 (CSP),初始化 PasswordDeriveBytes 類別的新執行個體。

PasswordDeriveBytes(String, Byte[])

使用用來衍生金鑰的密碼和金鑰 Salt,初始化 PasswordDeriveBytes 類別的新執行個體。

PasswordDeriveBytes(String, Byte[], CspParameters)

使用用來衍生金鑰的密碼、金鑰 Salt 和密碼編譯服務提供者 (CSP),初始化 PasswordDeriveBytes 類別的新執行個體。

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

使用用來衍生金鑰的密碼、金鑰 Salt、雜湊名稱和重複次數,初始化 PasswordDeriveBytes 類別的新執行個體。

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

使用用來衍生金鑰的密碼、金鑰 Salt、雜湊名稱、重複次數和密碼編譯服務提供者 (CSP),初始化 PasswordDeriveBytes 類別的新執行個體。

屬性

HashName

取得或設定用於操作的雜湊演算法名稱。

IterationCount

取得或設定操作的重複次數。

Salt

取得或設定用於操作的金鑰 Salt 值。

方法

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

PasswordDeriveBytes 物件衍生密碼編譯金鑰。

Dispose()

在衍生類別中覆寫時,將目前 DeriveBytes 類別的執行個體所使用的所有資源全部釋出。

(繼承來源 DeriveBytes)
Dispose(Boolean)

釋放 PasswordDeriveBytes 類別所使用的 Unmanaged 資源,並選擇性地釋放 Managed 資源。

Dispose(Boolean)

在衍生類別中覆寫時,釋出 DeriveBytes 類別使用的 Unmanaged 資源,並選擇性釋出 Managed 資源。

(繼承來源 DeriveBytes)
Equals(Object)

判斷指定的物件是否等於目前的物件。

(繼承來源 Object)
Finalize()

允許物件在記憶體回收進行回收之前,嘗試釋放資源並執行其他清除作業。

GetBytes(Int32)
已淘汰.

傳回似隨機金鑰位元組。

GetHashCode()

做為預設雜湊函式。

(繼承來源 Object)
GetType()

取得目前執行個體的 Type

(繼承來源 Object)
MemberwiseClone()

建立目前 Object 的淺層複製。

(繼承來源 Object)
Reset()

重設作業的狀態。

ToString()

傳回代表目前物件的字串。

(繼承來源 Object)

適用於

另請參閱