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 디스어셈블러) 도구, 16진수 편집기를 사용하거나 notepad.exe 같은 텍스트 편집기에서 어셈블리를 열어 어셈블리에서 검색할 수 있습니다.

생성자

PasswordDeriveBytes(Byte[], Byte[])

키를 파생시키는 데 사용할 암호 및 키 솔트를 지정하는 PasswordDeriveBytes 클래스의 새 인스턴스를 초기화합니다.

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

키를 파생시키는 데 사용할 암호, 키 솔트 및 CSP(암호화 서비스 공급자)를 지정하는 PasswordDeriveBytes 클래스의 새 인스턴스를 초기화합니다.

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

키를 파생시키는 데 사용할 암호, 키 솔트, 해시 이름 및 반복을 지정하는 PasswordDeriveBytes 클래스의 새 인스턴스를 초기화합니다.

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

키를 파생시키는 데 사용할 암호, 키 솔트, 해시 이름, 반복 횟수 및 CSP(암호화 서비스 공급자)를 지정하는 PasswordDeriveBytes 클래스의 새 인스턴스를 초기화합니다.

PasswordDeriveBytes(String, Byte[])

키를 파생시키는 데 사용할 암호 및 키 솔트를 사용하여 PasswordDeriveBytes 클래스의 새 인스턴스를 초기화합니다.

PasswordDeriveBytes(String, Byte[], CspParameters)

키를 파생시키는 데 사용할 암호, 키 솔트 및 CSP(암호화 서비스 공급자) 매개 변수를 사용하여 PasswordDeriveBytes 클래스의 새 인스턴스를 초기화합니다.

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

키를 파생시키는 데 사용할 암호, 키 솔트, 해시 이름 및 반복 횟수를 사용하여 PasswordDeriveBytes 클래스의 새 인스턴스를 초기화합니다.

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

키를 파생시키는 데 사용할 암호, 키 솔트, 해시 이름, 반복 횟수 및 CSP(암호화 서비스 공급자) 매개 변수를 사용하여 PasswordDeriveBytes 클래스의 새 인스턴스를 초기화합니다.

속성

HashName

작업에 대한 해시 알고리즘의 이름을 가져오거나 설정합니다.

IterationCount

작업의 반복 횟수를 가져오거나 설정합니다.

Salt

작업의 키 솔트 값을 가져오거나 설정합니다.

메서드

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

PasswordDeriveBytes 개체에서 암호화 키를 파생시킵니다.

Dispose()

파생 클래스에서 재정의되는 경우 DeriveBytes 클래스의 현재 인스턴스에서 사용하는 리소스를 모두 해제합니다.

(다음에서 상속됨 DeriveBytes)
Dispose(Boolean)

PasswordDeriveBytes 클래스에 사용되는 관리되지 않는 리소스를 해제하고, 필요에 따라 관리되는 리소스를 해제합니다.

Dispose(Boolean)

파생 클래스에서 재정의할 경우, DeriveBytes 클래스에서 사용하는 관리되지 않는 리소스를 해제하고 관리되는 리소스를 선택적으로 해제합니다.

(다음에서 상속됨 DeriveBytes)
Equals(Object)

지정된 개체가 현재 개체와 같은지 확인합니다.

(다음에서 상속됨 Object)
Finalize()

가비지 컬렉션이 회수하기 전에 개체가 리소스를 해제하고 다른 정리 작업을 수행할 수 있게 합니다.

GetBytes(Int32)
사용되지 않습니다.

의사(pseudo) 무작위 키 바이트를 반환합니다.

GetHashCode()

기본 해시 함수로 작동합니다.

(다음에서 상속됨 Object)
GetType()

현재 인스턴스의 Type을 가져옵니다.

(다음에서 상속됨 Object)
MemberwiseClone()

현재 Object의 단순 복사본을 만듭니다.

(다음에서 상속됨 Object)
Reset()

작업의 상태를 다시 설정합니다.

ToString()

현재 개체를 나타내는 문자열을 반환합니다.

(다음에서 상속됨 Object)

적용 대상

추가 정보