다음을 통해 공유


PasswordDeriveBytes 클래스

PBKDF1 알고리즘의 확장을 사용하여 암호에서 키를 파생시킵니다.

네임스페이스: System.Security.Cryptography
어셈블리: mscorlib(mscorlib.dll)

구문

‘선언
<ComVisibleAttribute(True)> _
Public Class PasswordDeriveBytes
    Inherits DeriveBytes
‘사용 방법
Dim instance As PasswordDeriveBytes
[ComVisibleAttribute(true)] 
public class PasswordDeriveBytes : DeriveBytes
[ComVisibleAttribute(true)] 
public ref class PasswordDeriveBytes : public DeriveBytes
/** @attribute ComVisibleAttribute(true) */ 
public class PasswordDeriveBytes extends DeriveBytes
ComVisibleAttribute(true) 
public class PasswordDeriveBytes extends DeriveBytes

설명

이 클래스는 PKCS#5 v2.0 표준에 정의된 PBKDF1 알고리즘의 확장을 사용하여 암호에서 키 재료로 사용하는 데 적합한 바이트를 파생시킵니다. 이 표준은 IETF RRC 2898에 문서화되어 있습니다.

Security note보안 참고

소스 코드에 하드 코딩된 암호를 추가하면 안 됩니다. 하드 코딩된 암호는 16진수 편집기인 MSIL 디스어셈블러(Ildasm.exe) 도구를 사용하거나 notepad.exe 같은 텍스트 편집기에서 어셈블리를 여는 방식으로 해당 어셈블리에서 쉽게 검색할 수 있습니다.

예제

다음 코드 예제에서는 PasswordDeriveBytes 클래스를 사용하여 암호에서 키를 만듭니다.

Imports System
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:")

        '********************************************************
        '* Security Note: Never hard-code a password within your
        '* source code.  Hard-coded passwords can be retrieved 
        '* from a compiled assembly.
        '********************************************************
        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 add it to the Key property.
            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
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:");

        //********************************************************
        //* Security Note: Never hard-code a password within your
        //* source code.  Hard-coded passwords can be retrieved 
        //* from a compiled assembly.
        //********************************************************

        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 add it to the Key property.
            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 - 1; x++)
        {
            Buffer[x] = 0;
        }
    }
}
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 add it to the Key property.
        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();
}

상속 계층 구조

System.Object
   System.Security.Cryptography.DeriveBytes
    System.Security.Cryptography.PasswordDeriveBytes

스레드로부터의 안전성

이 형식의 모든 public static(Visual Basic의 경우 Shared) 멤버는 스레드로부터 안전합니다. 인터페이스 멤버는 스레드로부터 안전하지 않습니다.

플랫폼

Windows 98, Windows 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

.NET Framework에서 모든 플래폼의 모든 버전을 지원하지는 않습니다. 지원되는 버전의 목록은 시스템 요구 사항을 참조하십시오.

버전 정보

.NET Framework

2.0, 1.1, 1.0에서 지원

참고 항목

참조

PasswordDeriveBytes 멤버
System.Security.Cryptography 네임스페이스

기타 리소스

암호화 서비스